angular - 如何在 Angular 中创建一个公共子组件
解决方案
父组件不能使用数据绑定来读取子属性或调用子方法。您可以通过为子元素创建模板引用变量,然后在父模板中引用该变量来完成这两项操作,如下例所示。
下面是一个子 CountdownTimerComponent,它反复倒计时到零并发射火箭。它具有控制时钟的启动和停止方法,并在自己的模板中显示倒计时状态消息。
import { Component, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-countdown-timer',
template: '<p>{{message}}</p>'
})
export class CountdownTimerComponent implements OnInit, OnDestroy {
intervalId = 0;
message = '';
seconds = 11;
clearTimer() { clearInterval(this.intervalId); }
ngOnInit() { this.start(); }
ngOnDestroy() { this.clearTimer(); }
start() { this.countDown(); }
stop() {
this.clearTimer();
this.message = `Holding at T-${this.seconds} seconds`;
}
private countDown() {
this.clearTimer();
this.intervalId = window.setInterval(() => {
this.seconds -= 1;
if (this.seconds === 0) {
this.message = 'Blast off!';
} else {
if (this.seconds < 0) { this.seconds = 10; } // reset
this.message = `T-${this.seconds} seconds and counting`;
}
}, 1000);
}
}
承载定时器组件的 CountdownLocalVarParentComponent 如下:
import { Component } from '@angular/core';
import { CountdownTimerComponent } from './countdown-timer.component';
@Component({
selector: 'app-countdown-parent-lv',
template: `
<h3>Countdown to Liftoff (via local variable)</h3>
<button (click)="timer.start()">Start</button>
<button (click)="timer.stop()">Stop</button>
<div class="seconds">{{timer.seconds}}</div>
<app-countdown-timer #timer></app-countdown-timer>
`,
styleUrls: ['../assets/demo.css']
})
export class CountdownLocalVarParentComponent { }
父组件不能数据绑定到子组件的 start 和 stop 方法,也不能绑定到它的 seconds 属性。
您可以在代表子组件的标记上放置一个局部变量#timer。这为您提供了对子组件的引用以及从父模板中访问其任何属性或方法的能力。
我希望这个例子对你有帮助
推荐阅读
- node.js - Firestore 导入数据文件未正确保存(ä、ö、ü、á 显示为符号)
- javascript - Firebase Scheduled Cloud Function 执行时如何获取时间?
- java - 由于缺少 JavaVM 框架,JavaCPP 在 Xcode 12.2 更新后在 macOS 上构建失败
- python - 可视化 Pandas 系列中出现频率最高的单词
- javascript - webpack和webpack-dev-server安装报错
- javascript - 组件位置 react dom
- python - 在 MIPS 中编写一个函数,该函数将表示整数(以给定基数)的字符串转换为以 10 为基数的相应数字
- sql - C++/CLI SQL 使用 ConnectionString 和参数作为字符串
- node.js - 有没有办法限制收到的请求以模拟服务器超时?
- r - 来自多个列的平均值(错误消息)