angular4,angular6 父組件異步獲取數據傳值子組件 undefined 問題


 

通過輸入和輸出屬性 實現數據在父子組件的交互
在子組件內部使用@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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM