[英]Angular 14 calling Child Component method from Parent Component
當我嘗試從 Parent 調用 childComponent 方法時出現錯誤
**兒童TS。 **
export class ChildComponent implements OnInit {
ChildMethod(){
console.log('test');
}
constructor() { }
}
**父 T **
@ViewChild(ChildComponent , {static : false}) child!:ChildComponent ;
CallChild(){
this.child.ChildMethod();
}
當我調用 CallChild 時出現此錯誤無法在 GpmainComponent.CallChild (gpmain.component.ts:39:16) 讀取未定義的屬性(讀取“ChildMethod”)
嘗試在構造函數中聲明您的子組件。
在 Parent.ts 中:
constructor(private child: ChildComponent) {}
CallChild() {
this.child.ChildMethod();
}
這可能取決於您何時調用CallChild
。
如果您在呈現視圖之前調用它,則this.child
將是undefined
,從而導致錯誤
這與static: false
和時序有關。
當設置為 false 時, ViewChild
查詢將在更改檢測運行之后和ngAfterViewInit
之前得到解決。 這意味着如果您嘗試在ngOnInit
中調用,那么child
將是未定義的。
您有 2 個選擇:
static: true
如果孩子不在*ngIf
下則為 true 然后它將更快地解決並在ngOnInit
中可用感謝您抽出時間回答問題。 我在 ngAfterViewInit 中嘗試了 true 和 false。
在兩個組件都從父組件上的按鈕初始化后,我正在調用子組件。
<button (click)="CallChild()" class="btn btn-link">load Child</button>
CallChild(){
this.child.ChildMethod();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.