Cannot read properties of undefined (reading 'nativeElement') in angular using agm/core

127 Views Asked by At

I am using agm/core for searching places. As guidelines I added required variables and code

Here is my code

import { MapsAPILoader } from '@agm/core';

@ViewChild('search') public searchElementRef: ElementRef;

I called in ngOnInit() function

 let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);

I added google api keys in app.module.ts

.html

\<input name="customer_address" formControlName="customer_address" type="text"
class="form-control" (keydown.enter)="$event.preventDefault()"
placeholder="Search Nearest Location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search\>

Error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'nativeElement')

1

There are 1 best solutions below

0
endlacer On

When the ngOnInit()-lifecylce runs, the DOM isn't rendered yet, which means the html element #search does not exist yet.

Try the ngAfterViewInit()-hook!