问题描述:

I want to use Place Autocomplete from Google to an input that is part of an Angular 2 template. I know I can access the element using ElementRef but it doesn't seem to be the best way and I want to do my best with this.

To test a different approach, instead looking for the element I want to apply the script to I used a click event like this:

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

Then on my angular component I have:

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

}

This works pretty well! But the thing is that I have to click my input to load the Autocomplete script.

Is there any event like 'load' for inputs or workaround so the script is loaded straight away?

网友答案:

When you add a template variable (myInput) to an element in your template you can access that element using @ViewChild('myInput'). It returns an ElementRef and its nativeElement is a reference to your input element:

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

See also angular 2 / typescript : get hold of an element in the template

相关阅读:
Top