Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 viewChild returns undefined

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.

like image 840
Nesan Mano Avatar asked Jun 03 '19 22:06

Nesan Mano


People also ask

What does ViewChild return?

The ViewChild decorator returns the first element that matches a given directive, component, or template reference selector.

What is the use of ViewChild in angular 8?

ViewChildlink Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

Can we access ViewChild in Ngoninit?

In order to get @ViewChild property inited, you need to call it in ngAfterViewInit lifecycle hook. ngAfterViewInit makes sure that the property is initialized (if there is a view child in template).


1 Answers

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; 
like image 70
Manoj De Mel Avatar answered Sep 18 '22 16:09

Manoj De Mel