子组件暴露一个 EventEmitter 属性,当事件发生时,子组件利用该属性 emits(向上弹射)事件。父组件绑定到这个事件属性,并在事件发生时做出回应。子组件的 EventEmitter 属性是一个输出属性,一般带有@Output 装饰器(只推荐使用此种方式来实现子父组件通讯)typescript
- 子组件代码
@Output() onVoted = new EventEmitter<boolean>(); vote(agreed: boolean) { this.onVoted.emit(agreed); }
- 父组件代码
<app-voter *ngFor="let voter of voters" [name]="voter" (onVoted)="onVoted($event)"> </app-voter>
父组件与子组件经过本地变量互动app
<app-countdown-timer #timer></app-countdown-timer>
#timer就表明了子组件,可是模板变量只能在模板中使用,不过咱们能够依靠函数参数实现更多可能函数
<app-countdown-timer #timer></app-countdown-timer> <button (click)=func(#timer)></button> func(timer){ timer.log(); // 调用了子组件timer的log方法 }
父组件使用@ViewChild()实现与子组件通讯this
import { ChildComponent } from './child.component'; @ViewChild(ChildComponent) private childComponent: ChildComponent; log(){ this.childComponent.son() ; // 调用了子组件的son()方法 }
接着上面的,若是须要在父组件页面渲染子组件的变量.net
content() { // 在父组件声明一个方法 } ngAfterViewInit() { // 在今生命周期钩子让此函数变成一个返回子组件变量的函数,不可缺乏setTimeout // 缘由: Angular 会调用 ngAfterViewInit 生命周期钩子,但这时候再更新父组件视图的倒计时就已经太晚了。Angular 的单向数据流规则会阻止在同一个周期内更新父组件视图。应用在显示秒数以前会被迫再等一轮。 setTimeout(() => this.content = () => this.cameraComponent.title, 0); }