1

I've upgraded to Angular 8.2.3 and converted all my ViewChild calls to include the static parameter. Now I am having an issue accessing components if they are wrapped in an *ngIf.

Previously this worked and I was able to call the component's method:

html:

<div *ngIf="someBooleanResult">
  ...
  <MyComponent #mycomponent1></MyComponent>
  ...
</div>

ts:

...

@ViewChild('mycomponent1') mycomponent1: MyComponent;

...

ngAfterViewInit () {
  if(someBooleanResult) {
    this.mycomponent1.someMethod();
  }
}

Now, in Angular 8, mycomponent1 is always undefined with this @ViewChild call (I also tried static: true but that didn't work either):

@ViewChild('mycomponent1', { static: false}) mycomponent1: MyComponent;

What am I missing about the new ViewChild design?

Alex
  • 1,353
  • 3
  • 20
  • 31
  • The answer to [this question](https://stackoverflow.com/q/51566012/1009922) will probably solve your problem. – ConnorsFan Aug 28 '19 at 19:10

1 Answers1

1

I faced the same problem in work today, the answer from Günter Zöchbauer solved the issue for me on this link:

@ViewChild in *ngIf

Also be aware, since you are modifying a value during Angular is detecting changes in the data which you would like to display, it can result in "Expression has changed after it was checked" error which also happened to me after using the solution.

You can have a detailed description about aswell here: https://blog.angular-university.io/angular-debugging

Patrik Alexits
  • 987
  • 9
  • 24
  • Gunter's answer is for viewchildren, not viewchild – Alex Aug 28 '19 at 20:02
  • @Alex The first thing to consider is that you need to wait for the view to be initialized before you can access your ViewChild, so you should access to the component in the AfterViewInit method. However, even if you access to the child component in the AfterViewInit, sometimes the ViewChild was still returning null. The problem can be caused by the *ngIf or other directive. The solution is to use the ViewChildren instead of ViewChild and subscribe the changes subscription that is executed when the component is ready. – Patrik Alexits Aug 28 '19 at 20:11
  • @Alex it's similar here aswell: https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined – Patrik Alexits Aug 28 '19 at 20:17
  • Yes, I see. The viewchildren trick worked. Not sure why all of a sudden this is a problem in 8 vs 7. Thanks. – Alex Aug 28 '19 at 20:55
  • The answer from Sviatoslav Oleksiv also worked and is more intuitive for Angular 8 I think – Alex Aug 28 '19 at 21:08
  • @Alex well, I'm glad at least it could lead you to a solution, in my case it wasn't working not sure why, that's why I suggested Günter's answer. – Patrik Alexits Aug 28 '19 at 21:10