【问题标题】:Applying script to input on Angular 2将脚本应用于 Angular 2 上的输入
【发布时间】:2016-05-03 13:30:50
【问题描述】:

我想将 Google 的 Place Autocomplete 用于作为 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);
}

这很好用!但问题是我必须点击我的输入来加载自动完成脚本。

是否有任何事件,例如输入的“加载”或解决方法,以便立即加载脚本?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

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

    【讨论】:

    • 太好了,谢谢。该函数应该在 ngAfterViewInit 中调用,对吗? this.initializeCityInput(myInput)?
    • 对!抱歉,忘记添加该行:-/
    猜你喜欢
    • 2018-11-10
    • 2017-05-17
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    相关资源
    最近更新 更多