Angular6 @ViewChild undefined with ngIf Angular6 @ViewChild undefined with ngIf angular angular

Angular6 @ViewChild undefined with ngIf


As Angular's Doc says:

"True to resolve query results before change detection runs. If any query results are inside a nested view (such as *ngIf), the query is resolved after change detection runs."

So, passing the param { static: false } to @ViewChild resolve the problem, as it is accessed on ngAfterViewInit, instead on { static: true } is accessed before change detection runs so on ngOnInit.


ngIf will remove you component from the DOM. So it becomes undefined.If you use [hidden]="!showFirstChild" instead, it will be only hidden, and will be available in the component.

Here is a stackblitz where you can check this.


Try running change detection in between to ensure the DOM template is reading the DOM after the change in reset.

In template:

<first-child #firstChild *ngIf="showFirtChild"></first-child>

In controller:

import { ChangeDetectorRef } from '@angular/core';export class exampleClass implements {  @ViewChild('firstChild') public firstChildComp: MyFirstChildComponent;  public fcomp: any;  public showFirtChild: boolean;  constructor(private ref: ChangeDetectorRef,            //your services) {}  public ngAfterViewInit()   {      this.showFirtChild = true;      this.ref.detectChanges();      this.fcomp = this.firstChildComp;  }  public reset(): void   {      this.fcomp.fillTable();  }}

ChangeDetectorRef Documentation for further reading.