通過輸入和輸出屬性 實現數據在父子組件的交互
在子組件內部使用@input接受父組件傳入數據,使用@output傳出數據到父組件
詳細標准講解參考官方文檔
https://angular.cn/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding
但是我在開發中遇到這樣一個問題,當父組件傳入的數據是在網絡請求回來之后才被賦值,這時的子組件已經初始化結束,就會存在異步的問題
解決辦法是使用ngOnChanges()來截聽輸入屬性值的變化,然后在自己的代碼里處理數據;
代碼如下:
父組件使用子組件代碼 parent傳入child傳出
父: html
<child-app [parent]="parent" (child)="getChild($event)"></child-app>
父:ts
getChild(child) {
//子組件返回數據
console.log(child)
}
子:ts
@Component({
selector: 'child-appt',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
@Input() parent: any;
@Output() child = new EventEmitter<any>()
ngOnChanges(changes: SimpleChanges): void {
if (changes['parent'] !== undefined) {
this.curParent = changes['parent'].currentValue;
}
}
this.child.emit(data);