【发布时间】:2018-05-01 02:28:11
【问题描述】:
我正在尝试在我的应用程序中使用 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 种不同的方法,但没有成功
【问题讨论】:
-
我们能看到
addressElement的声明吗?此外,输入元素是在ngFor循环内还是在具有ngIf条件的祖先内? -
至于“技巧”,您可以尝试:
const addressInput = document.getElementById('address');,并将this.addressElement.nativeElement替换为addressInput(尽管使用document.getElementById不是Angular 访问元素的方式)。跨度> -
请出示
addressElement的声明,这是最重要的。对于“技巧”,请尝试:const addressInput = document.getElementById('address') as HTMLInputElement;。 -
模板变量
#address绑定到ngModel。您应该在输入元素中定义另一个,例如#address1,并在@ViewChild('address1')中使用它。这应该有效(而不是使用document.getElementById)。不过,我不确定它是否有助于解决其他问题。 -
@ConnorsFan 所以也许这是修复的一部分。我还注意到自动完成在模态后面,所以我添加了 `.pac-container { z-index: 10000 !important; } ' 这使它出现在模式的顶部。非常感谢这个人!!如果您愿意,请将其作为答案发布,以便我将其作为正确答案,您可以获得一些积分
标签: angular google-maps google-maps-api-3