khaled mahmoud
khaled mahmoud

Reputation: 97

ViewChild element undefined when referenced before view initialized

what I'm trying to achieve is the below

use a string to access ViewChild then add class to it

but it gives this error " Cannot read property 'nativeElement' of undefined"

@ViewChild('projects', { static: false }) projects: ElementRef;

someFunc(){

  let data = 'projects'
  let elementToMarkActive = this[data]

  elementToMarkActive.nativeElement.classList

}

Upvotes: 0

Views: 284

Answers (1)

Chris Baker
Chris Baker

Reputation: 50602

Elements selected using ViewChild decorators are not available in ngOnInit (or any other lifecycle phase prior to view rendering and initial change detection) without the static argument set to true.

Please reference the documentation for ViewChild for more information.

Upvotes: 2

Related Questions