Angular Google Maps组件TypeError:无法读取属性' nativeElement'未定义的

时间:2018-06-05 07:13:52

标签: javascript angular google-maps typescript angular-cli

所以我正在尝试为 AGM 创建一个自动填充输入,到目前为止一直很好,但是当我将组件(app-agm-input)放入我的{{1}时},我收到以下错误:

enter image description here

这是我的组件的样子:

app.component.html

这是我的模块的样子:

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;
                }
            });
        });
    });
}
}

注意我已删除了API密钥,以便进行审核。

这就是我的组件的html文件的样子:

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 {}

1 个答案:

答案 0 :(得分:1)

您指的是错误的变量名称

像这样做你的代码 -

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