Angular v8 - @ViewChild static true or false
From the documentation:
How do I choose which static flag value to use: true or false?
In the official API docs, we have always recommended retrieving query results in ngAfterViewInit for view queries and ngAfterContentInit for content queries. This is because by the time those lifecycle hooks run, change detection has completed for the relevant nodes and we can guarantee that we have collected all the possible query results.
Most applications will want to use {static: false} for the same reason. This setting will ensure query matches that are dependent on binding resolution (e.g. results inside *ngIfs or *ngFors) will be found by the query.
There are rarer cases where {static: true} flag might be necessary (see answer here).
https://angular.io/guide/static-query-migration
Use { static: true }
when you want to access the ViewChild
in ngOnInit
.
Use { static: false }
will be accessible only in ngAfterViewInit
. This is also what you want to do for when you have a structural directive (*ngIf
etc.) in your template.
In most cases { static: false }
will work.
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit, AfterViewInit
{
@ViewChild('elementA', { static: true }) elementStatic: ElementRef<HTMLElement>;
@ViewChild('elementB', { static: false }) elementDynamic: ElementRef<HTMLElement>;
public ngOnInit(): void
{
this.elementStatic.nativeElement; // Ok
this.elementDynamic.nativeElement; // ERROR TypeError: Cannot read property 'nativeElement' of undefined
}
public ngAfterViewInit(): void
{
this.elementStatic.nativeElement; // Ok
this.elementDynamic.nativeElement; // Ok
}
}
<div #elementA>A</div>
<div #elementB>B</div>
Update: Starting from Angular v9.x static has a default value of false.
Read more at: https://angular.io/api/core/ViewChild#viewchild