angular – @viewChild not working – cannot read property nativeElement of undefined

angular – @viewChild not working – cannot read property nativeElement of undefined

@ViewChild(keywords-input) keywordsInput; doesnt 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

Youll 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 dont use *ngIf.

Instead use a class to show/hide your element being hidden.

<div [class.show]=shouldShow>...</div>

angular – @viewChild not working – cannot read property nativeElement of undefined

The accepted answer is correct in all means and I stumbled upon this thread after I couldnt 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;

Leave a Reply

Your email address will not be published.