// 父组件不能使用数据绑定来读取子组件的属性或调用子组件的方法。但可以在父模版里,新建一个本地变量来代表子组件,然后利用这个变量来读取子组件的属性和调用子组件的方法import{Component,OnDestroy,OnInit}from'@angular/core';
@Component({selector: 'countdown-timer',template: '<p>{{message}}</p>'})exportclassCountdownTimerComponentimplementsOnInit,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`;}privatecountDown(){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;}// resetthis.message=`T-${this.seconds} seconds and counting`;}},1000);}}
import{Component}from'@angular/core';import{CountdownTimerComponent}from'./countdown-timer.component';
@Component({selector: '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> <countdown-timer #timer></countdown-timer> `,styleUrls: ['demo.css']})exportclassCountdownLocalVarParentComponent{}
父组件调用 ViewChild
import{AfterViewInit,ViewChild}from'@angular/core';import{Component}from'@angular/core';import{CountdownTimerComponent}from'./countdown-timer.component';
@Component({selector: 'countdown-parent-vc',template: ` <h3>Countdown to Liftoff (via ViewChild)</h3> <button (click)="start()">Start</button> <button (click)="stop()">Stop</button> <div class="seconds">{{ seconds() }}</div> <countdown-timer></countdown-timer> `,styleUrls: ['demo.css']})exportclassCountdownViewChildParentComponentimplementsAfterViewInit{
@ViewChild(CountdownTimerComponent)//通过 ViewChild 装饰器倒入引用 ,将子组件注入到 timerComponentprivatetimerComponent: CountdownTimerComponent;seconds(){return0;}ngAfterViewInit(){// Redefine `seconds()` to get from the `CountdownTimerComponent.seconds` ...// but wait a tick first to avoid one-time devMode// unidirectional-data-flow-violation errorsetTimeout(()=>this.seconds=()=>this.timerComponent.seconds,0);}start(){this.timerComponent.start();}stop(){this.timerComponent.stop();}}