Angular 8 viewChild returns undefined

Nesan Mano picture Nesan Mano · Jun 4, 2019 · Viewed 25.2k times · Source

I am trying to access the childView instance but it keeps saying the the childView is undefined.

Here is my code for childViews:

@ViewChild(CreateQuestionnaireComponent,{ read: true, static: false })  private childQuestionnaireDialog:CreateQuestionnaireComponent;
@ViewChild(ProjectNavbarComponent,{ read: true, static: false })  private childProjectNavBar:ProjectNavbarComponent;
@ViewChild(QuestionnaireNodeComponent,{ read: true, static: false }) private childQuestionnaireNode:QuestionnaireNodeComponent;
....

onCreateTerminal() {
        this.childQuestionnaireDialog.generateQuestionnaireDropDownList();
        this.childQuestionnaireDialog.resetFields();
        this._hideQuestionnaireDialog = false;
        this._modalTitle = 'New Terminal';
        this._placeHolderText = 'Terminal Questionnaire Title';
        this._terminal = true;
    }

...

It says :this.childQuestionnaireDialog is undefined".

It was working with Angular 7.

As per my new knowledge, the @viewChild takes a flag called static. If we put the flag to true, the parent component tries to get a reference to the childView during its own creation. In other words, we could have an instance of the childView in the onInit() method of the parent Component.Basically a one time access because we won't be able to access in any other methods.

The flag set to false, is basically the new way in ivy renderer.

The problem in my case, neither options are working.

Answer

Manoj De Mel picture Manoj De Mel · Jul 1, 2019

I had a similar problem where ViewChild component is undefined in onInit() method.

This fixed the issue:

// Ensure Change Detection runs before accessing the instance
@ContentChild('foo', { static: false }) foo!: ElementRef;

// If you need to access it in ngOnInit hook
@ViewChild(TemplateRef, { static: true }) foo!: TemplateRef;