gpt4 book ai didi

javascript - 将脚本应用于 Angular 2 上的输入

转载 作者:行者123 更新时间:2023-11-28 06:04:36 24 4
gpt4 key购买 nike

我想将 Google 的 Place Autocomplete 用于作为 Angular 2 模板一部分的输入。我知道我可以使用 ElementRef 访问该元素,但这似乎不是最好的方法,我想尽我所能。为了测试不同的方法,我使用了如下的点击事件来寻找我想要应用脚本的元素:

<input type="text" id="city" (click)="initializeCityInput($event)" />

然后在我的 Angular 分量上:

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);
}

这个效果非常好!但问题是我必须单击我的输入才能加载自动完成脚本。

是否有任何像“加载”这样的事件用于输入或解决方法,以便立即加载脚本?

最佳答案

当您将模板变量 (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

关于javascript - 将脚本应用于 Angular 2 上的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36995946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com