我想将Google的地方自动填充功能用于Angular 2模板中的输入。我知道我可以使用ElementRef访问该元素,但它似乎不是最好的方式,我想尽我所能。 要测试不同的方法,而是寻找我想要应用脚本的元素,我使用了这样的点击事件:
<input type="text" id="city" (click)="initializeCityInput($event)" />
然后在我的角度组件上我有:
initializeCityInput(event) {
let input: HTMLInputElement = event.currentTarget;
let options = {
types: ['(cities)'],
componentRestrictions: { country: 'au' }
};
let autocomplete = new this.w.google.maps.places.Autocomplete(input, options);
}
这很好用!但问题是我必须单击我的输入才能加载自动完成脚本。
是否存在输入或解决方法的“加载”等事件,以便立即加载脚本?
答案 0 :(得分:0)
将模板变量(myInput
)添加到模板中的元素后,您可以使用@ViewChild('myInput')
访问该元素。它返回ElementRef
,其nativeElement
是对输入元素的引用:
@Component({
selector: '...',
template: `
<input #myInput type="text" id="city" />
`
})
class MyAutoComplete {
@ViewChild('myInput') myInput;
ngAfterViewInit() {
this.initializeCityInput(myInput)
}
initializeCityInput(event) {
let options = {
types: ['(cities)'],
componentRestrictions: { country: 'au' }
};
let autocomplete = new this.w.google.maps.places.Autocomplete(myInput.nativeElement, options);
}
}
另见angular 2 / typescript : get hold of an element in the template