簡體   English   中英

父組件通過ViewChild訪問其子組件之一,但始終未定義

[英]parent component accesses one of its child via ViewChild but it is always undefined

我的模板中有一個組件,其中另一個組件是我自己的:

<div (click)="onEditStarted()">
    ...
    <my-child *ngIf="someCondition"></my-child>
    ...
</div>

在父母中,我有:

@ViewChild(MyChildComponent) child: MyChildComponent;

但是在我需要child ,它是undefined

OnEditStarted() {
    ...
    setTimeout(() => this.child.someMethod(), 0);
   ...
}

我還嘗試否定someCondition並將其放入[hidden]屬性而不是*ngIf但它仍未undefined 有任何想法嗎?

我認為問題出在* ngIf指令中。 它正在殺死my-child組件,因此無法引用它。 您可以嘗試使用ViewChildren代替ViewChild或嘗試使用ng-template包裝ngIf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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