一.通過setter 截聽輸入屬性值的變
利用getter setter對值進行獲取和處理
二. ngOnChanges()來截聽輸入屬性值的變化
監測輸入屬性值的變化
當需要監視多個、交互式輸入屬性的時候,本方法比用屬性的 setter 更合適。
三.父組件監聽子組件的事件(組件輸入輸出)
@Input() name = '';
//父組件->向子組件傳遞數據。
@Output() voted = new [EventEmitter]<boolean>();
//父組件可以獲取子組件的信息,同時父組件要創建html監聽
EventEmitter是node.js的一個監聽器。
四.父級調用 @ViewChild()
@ViewChild可以獲取到當前組件視圖中的單個元素
@ViewChildren獲取子組件對象列表
1.局部變量訪問
@ViewChild('changeColor',{static:true}) changeColor;
2.直接指定組件類
父類的html
<app-home [items]="items" #home ></app-home>
<!-- #home要寫在子控件的里面 -->
<button (click)="appComponentAction()" >父級點擊這里</button>
父類的Ts
// 子類的聲明
@ViewChild('home',{static:true}) home:HomeComponent;
// 實現點擊事件
appComponentAction(): void{
// 通過home子類調用屬性和方法
this.home.textColor1 = 'd';
this.home.run();
}
}
子類只需要實現這倆個方法和公開屬性就好
@Input()
set textColor1(value:string){
console.log('textcolor:'+value);
this.textColorStr = value;
}
get textColor1():string{
return this.textColorStr ;
}
run(){
console.log('running');
}