@ViewChild returns undefined

ViewChild() works fine on latest plunker Angular version with the scenario you describe.

Demonstration in this plunker : https://plnkr.co
/edit/KzWnkE5Hvp7NUow6YAxy

EDIT: Here is a replacement StackBlitz for the above Plunker: https://stackblitz.com/edit/angular-ivy-pzaglm

component :

ngAfterViewInit() {
    console.log(this.testView); // correctly outputs the element in console, not undefined
}
  • Check that ElementRef and ViewChild are correctly imported from ‘@angular/core’

  • Your element might simply not be there at the time of AfterViewInit (in case there is a *ngIf, for instance. (seems the case as per your comments)

In the latter case, you can use a wrapper element and ViewChildren , that emits some event when a new child element is added – more info on documentation here : https://angular.io/api/core/ViewChildren

note that there might be some issue with native div as per this question : @ViewChildren does not get updated with dynamically added DOM elements , but this can be worked around by using a new component that wraps your div, for instance.

EDIT

Or you can also use a timeout to wait for the component to be rendered. I must say that I find this solution ‘dirty’, but glad it works for you 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)