the new static option for @ViewChild in Angular 8

the new static option for @ViewChild in Angular 8

  • { static: true } needs to be set when you want to access the ViewChild in ngOnInit.
  • { static: false } can only be accessed in ngAfterViewInit. This is also what you want to go for when you have a structural directive (i.e. *ngIf) on your element in your template.

Static queries are filled before ngOnInit, while dynamic queries (static: false) are filled after. In other words, if a viewchild is now null in ngOnInit after you set static: false, you should consider changing to static: true or move code to ngAfterViewInit.

See https://github.com/angular/angular/blob/master/packages/core/src/view/view.ts#L332-L336

The other answers are correct and explain why this is the case: Queries dependant on structural directives, e.g. a ViewChild reference inside an ngIf, should run after the conditional of this directive has been resolved, ie after change detection. However, one may safely use static: true and thus resolve the queries before ngOnInit for unnested references. Imho this particular case bears mentioning as a null exception could likely be the first way you’ll encounter this particularity, as it was for me.

From answers on stackoverflow.com.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.