F
F
FlatUser2020-06-01 20:35:09
Angular
FlatUser, 2020-06-01 20:35:09

@ViewChild throws undefined due to ngIf, how to solve the problem?

I have a parent component and it looks like this.

export class ParentComponent {
  @ViewChild(ChildComponent) childComponent: ChildComponent;
  public showChild: boolean = false;

  clickHandler() {
     this.showChild = true;
     this.childComponent.setSomething()
  }
}


There is a showChild variable that shows the childComponent via ngIf ChildComponent has a setSomething() method that I call in the parent component's click handler. ClickHandler() triggers an error
<child *ngIf="showChild "></child >


ERROR TypeError: Cannot read property 'setSomething' of undefined

Since ngIf has not yet worked and the component has not been rendered, even though it is preceded by this.showChild = true;

How to solve this problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question