簡體   English   中英

Angular 14 從父組件調用子組件方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM