我正在尝试使用我的应用中的google mapsAPI对地址进行自动填充,但我不断收到“InvalidValueError:不是HTMLInputElement的实例”错误。以下是我尝试过的事情
表单内的html输入。正如你所看到的那样,我尝试了焦点技巧,它也没有用。
<input id="address" type="text" name="address" #address="ngModel" [(ngModel)]="markersService.selectedMarker.address" placeholder="Address"
autocorrect="off"
autocapitalize="off"
spellcheck="off"
class="inputFields"
required
(focus)="autocompleteSearch()"/>
.ts文件
//I implemented this in an app with Angular 4 and it worked, now with Angular5 it' doesn't
ngAfterViewInit() {
this.autocompleteSearch();
}
autocompleteSearch() {
/*
I tried this trick based on some answers I saw in different places, but it didn't work
var addressInput = document.getElementById('address').getElementsByTagName('input')[0];
of course I was passing this in the code below instead of the addressElement
*/
this.mapsAPILoader.load().then(
()=>{
let autocomplete = new google.maps.places.Autocomplete(this.addressElement.nativeElement, { types:["address"]});
autocomplete.addListener('places_changed', ()=> {
this.ngZone.run(()=> {
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
if(place.geometry === undefined || place.geometry === null) {
return;
}
});
})
}
)
}
我尝试了4种不同的东西,没有运气让它发挥作用
答案 0 :(得分:1)
模板参考变量#address
与ngModel
相关联。您可以定义另一个,例如#address1
:
<input #address1 #address="ngModel" ... >
并使用它来访问代码中的元素:
@ViewChild('address1') public addressElement: ElementRef;
...
let inputElement = this.addressElement.nativeElement as HTMLInputElement;