Angular4 How to know when a ViewChild has been reset

Viewed 13681

Here is the template of main.html :

<button (click)="displayAndUseMyCustomComp()"></button>
<my-custom-comp *ngIf="isMyCustomCompDisplayed" #myCustomComp="myCustomComp"></my-custom-comp>

and main.component.ts :

export class MainComponent {
  constructor() {}
  private isMyCustomCompDisplayed boolean = false
  @ViewChild('myCustomComp') myCustomComp: MyCustomComp

  displayAndUseMyCustomComp() {
     this.isMyCustomCompDisplayed = true
     console.log(this.myCustomComp) // prints undefined 
     setTimeout(() => {
       console.log(this.myCustomComp) // prints {object}
     })
  }

}

What's happening is that my template isn't yet refreshed after I set isMyCustomCompDisplayed to true. However, if I use a setTimeout, myCustomComp gets updated and my issue goes away. It is midly hacky, and I was wondering what was the correct way of doing what I am trying to.

1 Answers
Related