angular - InvalidValueError:不是 HTMLInputElement Angular 5 的实例
问题描述
我正在尝试在我的应用程序中使用 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 种不同的东西,没有运气让它工作
解决方案
模板引用变量#address
绑定到ngModel
. 您可以定义另一个,例如#address1
:
<input #address1 #address="ngModel" ... >
并使用它来访问代码中的元素:
@ViewChild('address1') public addressElement: ElementRef;
...
let inputElement = this.addressElement.nativeElement as HTMLInputElement;
推荐阅读
- python - 如何在 Django 框架上列出特定邮政编码的 Kirana 商店/咖啡馆?
- java - 在java中转换为最接近的1000
- python - 如何从交替的布尔行创建一个新的 Pandas DataFrame,以便新的 DataFrame 可以绘制?
- python - 如何创建包含多个命令的可执行文件?
- spring - 从 Spring Boot 中的 Zalando 问题响应正文中自定义和删除不需要的字段
- javascript - 为什么在这个例子中他们将响应包装在另一个 Promise.all 中?
- spark-streaming - 为什么 Spark Streaming 任务的数量与 Kafka 分区不同?
- python - 使用 Python 替换文本文件中的一行中的一列
- android - 如何刷新片段中的onBindViewHolder方法
- android - 获取 DrawerLayout 必须在添加抽屉布局时使用 MeasureSpec.EXACTLY 进行测量