使用角度贴图自动完成功能(AGM)时出现此错误,
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
,将ElementRef
用于角度public searchElement: ElementRef;
。
我遇到错误:
public latitude: number;
public longitude: number;
public searchControl: FormControl;
public zoom: number;
@ViewChild("search")
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) {}
ngOnInit() {
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
//create search FormControl
this.searchControl = new FormControl();
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
//set latitude, longitude and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
在我的视图组件
中 <div class="form-group">
<input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
</div>
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
</agm-map>
我在两个组件中使用它,一个在另一个上工作罚款它会给那个错误。试图为元素引用使用不同的名称但是引发相同的错误。
答案 0 :(得分:0)
你应该声明一个像
这样的变量 @ViewChild("search") public searchElementRef: ElementRef;
而不是
public searchElement: ElementRef
这意味着searchElement
变量将模板中提到的search
模板引用称为(#search)
w.r.t input
元素。