Google オートコンプリートを実装すると、このエラーが発生します
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
私のコンポーネントはそれに似ています:
@ViewChild('search', {static:false})
public searchElementRef: ElementRef;
ngOnInit() {
this.mapsAPILoader.load().then(() => {
this.getMyUbication();
this.geoCoder = new google.maps.Geocoder;
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.lat = place.geometry.location.lat();
this.lng = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
この部分で、「未定義のプロパティ 'nativeElement'を読み取れません」というエラーが表示されます
HTML コード:
<input type="text" id="geoloc" matGoogleMapsAutocomplete [(ngModel)]="geolocation" [ngModelOptions]="{standalone: true}" class="form-control" placeholder="Geolocalización" (keydown.enter)="$event.preventDefault()" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search (onLocationSelected)="onLocationSelected($event)">
<ul>
<li style="color: #bd1f2d" *ngIf="errors && errors['getmyubication']">{{errors['getmyubication']}}</li>
</ul>
<div *ngIf="showMap" class="map_st001" style="background: #DDDDDD;">
<agm-map [latitude]="lat" [zoom]="zoom" [longitude]="lng" [scrollwheel]="null">
<agm-marker [latitude]="lat" [longitude]="lng" [markerDraggable]="true" (dragEnd)="markerDragEnd($event)"></agm-marker>
</agm-map>
</div>