@viewChild not working - cannot read property nativeElement of undefined
You'll also get this error if your target element is inside a hidden element. If this is your HTML:
<div *ngIf="false">
<span #sp>Hello World</span>
</div>
Your @ViewChild('sp') sp
will be undefined.
Solution
In such a case, then don't use *ngIf
.
Instead use a class to show/hide your element being hidden.
<div [class.show]="shouldShow">...</div>
The accepted answer is correct in all means and I stumbled upon this thread after I couldn't get the Google Map render in one of my app components.
Now, if you are on a recent angular version i.e. 7+ of angular then you will have to deal with the following ViewChild declaration i.e.
@ViewChild(selector: string | Function | Type<any>, opts: {
read?: any;
static: boolean;
})
Now, the interesting part is the static value, which by definition says
- static - True to resolve query results before change detection runs
Now for rendering a map, I used the following ,
@ViewChild('map', { static: true }) mapElement: any;
map: google.maps.Map;
I had a similar problem, but in my case I was trying to read the nativeElement
inside the ngOnInit
method:
@ViewChild('userNameInput') userNameInput: ElementRef<HTMLInputElement>;
...
ngOnInit(): void {
this.userNameInput.nativeElement.focus();
}
I've changed to ngAfterViewInit
and everything worked fine:
@ViewChild('userNameInput') userNameInput: ElementRef<HTMLInputElement>;
...
ngAfterViewInit(): void {
this.userNameInput.nativeElement.focus();
}
@ViewChild('keywords-input') keywordsInput;
doesn't match id="keywords-input"
id="keywords-input"
should be instead a template variable:
#keywordsInput
Note that camel case should be used, since -
is not allowed in template reference names.
@ViewChild()
supports names of template variables as string:
@ViewChild('keywordsInput') keywordsInput;
or component or directive types:
@ViewChild(MyKeywordsInputComponent) keywordsInput;
See also https://stackoverflow.com/a/35209681/217408
Hint:keywordsInput
is not set before ngAfterViewInit()
is called