Tanasos
Tanasos

Reputation: 4098

Angular Google Maps component TypeError: Cannot read property 'nativeElement' of undefined

So I am trying to create an autofill input for AGM, so far so good, but when I place the component (app-agm-input) inside my app.component.html, I get the following error:

enter image description here

Here is what my component looks like:

import {
    Component,
    OnInit,
    ViewChild,
    ElementRef,
    NgZone,
    Input
} from "@angular/core";
import { MapsAPILoader } from "@agm/core";
import {} from "@types/googlemaps";

@Component({
    selector: "app-agm-input",
    templateUrl: "./agm-input.component.html",
    styles: []
})
export class AgmInputComponent implements OnInit {
    @ViewChild("agmInput") public searchElement: ElementRef;

    @Input() placeholder: string;

    constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}

    ngOnInit() {
        this.mapsAPILoader.load().then(() => {
            let autocomplete = new google.maps.places.Autocomplete(
            this.searchElement.nativeElement,
            { types: ["address"] }
        );

        autocomplete.addListener("place_changed", () => {
            this.ngZone.run(() => {
                let place: google.maps.places.PlaceResult = autocomplete.getPlace();

                if (
                    place.geometry === undefined ||
                    place.geometry === null
                ) {
                    return;
                }
            });
        });
    });
}
}

Here is what my module looks like:

import { NgModule } from "@angular/core";
import { AgmInputComponent } from "./agm-input.component";
import { SharedModule } from "../../shared.module";
import { AgmCoreModule } from "@agm/core";

@NgModule({
    imports: [
        SharedModule,
        AgmCoreModule.forRoot({
            apiKey: "**key**",
            libraries: ["places"]
        })
    ],
    declarations: [AgmInputComponent],
    exports: [AgmInputComponent]
})
export class AgmInputModule {}

NOTE I have removed the API key, for reviewing purposes.

And this is how my component's html file looks like:

<input class="input" type="search" placeholder="{{placeholder}}" autocorrect="off" autocapitalize="off" spellcheck="off" #agmSearch>

Upvotes: 0

Views: 3263

Answers (1)

Pardeep Jain
Pardeep Jain

Reputation: 86730

You are referring to wrong variable name

do your code like this -

    @ViewChild("agmSearch") public searchElement: ElementRef;

Upvotes: 1

Related Questions