Angular6 @ViewChild undefined with ngIf

bigskull picture bigskull · Apr 10, 2019 · Viewed 21.4k times · Source

I've a problem using @ViewChild with a component showed through ngIf. I found various solutions but no one usefull for me. This is my main component, consisting of various step (I showed only 2 in code for brevity) with a button for forward navigation and a button to reset the component returning on first step. First step is showed on page opening:

...
<div class="my-container">
    <first-child *ngIf="showFirtChild"></first-child>
    <second-child *ngIf="showSecondChild"></second-child>
</div>
<button (click)="goToNextStep()"></button>
<button (click)="reset()"></button>
...
export class MainComponent implements OnInit {
    @ViewChild(FirstChild) private firstChildComp: MyFirstChildComponent;
    showFirtChild: boolean = true;

    ngOnInit() {
        //here firstChildComp is defined
    }

    //code for navigate through steps
    reset() {
        this.showFirtChild= true;
        this.firstChildComp.fillTable(); //fillTable is a function defined in MyFirstChildComponent
    }
...
}

During steps navigation the reference to firstChildComp is lost and when reset() is called, childComp results undefined. I know the cause is ngIf, so I tryed to use ngAfterViewInit:

ngAfterViewInit() {
    this.fcomp = this.firstChildComp;
}

reset() {
        this.showFirtChild= true;
        this.fcomp .fillTable();
}

but it doesn't resolve my problem. Any suggestion?

Answer

Eduardo Mihalache picture Eduardo Mihalache · Dec 13, 2019

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.