我正在尝试将Angular 6与Google Maps自动完成功能一起使用。 我在模态中有输入文本。 这是代码:
<input id="searchTextField" type="text" google-place (onSelect)="autoMaps()" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
autocompleteFn() {
const input = window.HTMLInputElement(document.getElementById('searchTextField'));
const autocomplete = new google.maps.places.Autocomplete(input);
console.log(el);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
const placee = autocomplete.getPlace();
console.log(placee.name);
console.log(placee.geometry.location.lat());
console.log(placee.geometry.location.lng());
let address = '';
if (placee.address_components) {
address = [
(placee.address_components[0] && placee.address_components[0].short_name || ''),
(placee.address_components[1] && placee.address_components[1].short_name || ''),
(placee.address_components[2] && placee.address_components[2].short_name || '')
].join(' ');
}
console.log(address);
});
}
运行它并打开模态时,出现此错误:
InvalidValueError:不是HTMLInputElement的实例
答案 0 :(得分:0)
您的输入元素(#searchTextField)本身就是
HTMLInputElement
也许您可以这样重写 autocompleteFn()的开头:
"font_grey"
获取文本输入元素的引用的另一种Angular方法是使用
@ViewChild
装饰器以查询视图。看起来就像在您的View-Class内部:
const input = document.getElementById('searchTextField');
console.log(input);
const autocomplete =
new google.maps.places.Autocomplete(input as HTMLInputElement);
...
并在您的模板文件中对应:
@ViewChild('searchTextField') input : ElementRef;
那样,您可以在函数中使用声明的变量 input ,如下所示:
<input #searchTextField ...
答案 1 :(得分:0)
只需将window.HTMLInputElement(document.getElementById('searchTextField'))
更改为document.getElementById('searchTextField') as HTMLInputElement
HTML
<input id="searchTextField" type="text" google-place (onSelect)="autoMaps()" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
ts
autocompleteFn() {
const input = document.getElementById('searchTextField') as HTMLInputElement;
const autocomplete = new google.maps.places.Autocomplete(input);
console.log(el);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
const placee = autocomplete.getPlace();
console.log(placee.name);
console.log(placee.geometry.location.lat());
console.log(placee.geometry.location.lng());
let address = '';
if (placee.address_components) {
address = [
(placee.address_components[0] && placee.address_components[0].short_name || ''),
(placee.address_components[1] && placee.address_components[1].short_name || ''),
(placee.address_components[2] && placee.address_components[2].short_name || '')
].join(' ');
}
console.log(address);
});
}