How can I get the wrapped input from an ion-input

2019-06-23 16:59发布

问题:

I'd like to attach an google.maps.places.Autocomplete to an ion-input, but in Ionic2 ion-input wraps the <input> element and I can't figure out how to get access to it.

I've tried creating a directive and using the passed in ElementRef

import {Directive, ElementRef, Input} from 'angular2/core';

@Directive({
    selector: '[location-picker]'
})

export class LocationPicker {
    constructor(el: ElementRef) {    
        console.log(el.nativeElement);    
    }
}

but nativeElement returns the wrapped input.

<ion-input location-picker="">
    <input class="text-input ng-valid ng-dirty ng-touched" type="text" placeholder="" aria-labelledby="lbl-6" location-picker="" autocomplete="off" autocorrect="off">
    <!--template bindings={}-->
    <!--template bindings={}-->
    <!--template bindings={}-->
</ion-input>

I've also tried creating a custom component similar to this and switching Searchbar to TextInput, but TextInput doesn't have.inputElement`.

Any ideas would be welcome.

Thanks!

回答1:

Not sure this is what you're looking for (don't know Ionic)

<ion-input location-picker="">
    <input #myInput class="text-input ng-valid ng-dirty ng-touched" type="text" placeholder="" aria-labelledby="lbl-6" location-picker="" autocomplete="off" autocorrect="off">
    <!--template bindings={}-->
    <!--template bindings={}-->
    <!--template bindings={}-->
</ion-input>
@ViewChild('myInput') input; 

ngAfterViewInit() {
  console.log(this.input.nativeElement.value);
}

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



回答2:

Had the same question. A combination of the accepted answer and the comments below it seemed to solve it for me.

Adding this function to my Directive seemed to do it. I'm using Typescript and the typings definition for googlemaps found here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/googlemaps/google.maps.d.ts

ngAfterViewInit() {
    var input: HTMLInputElement = <HTMLInputElement>this._el.querySelector("input");
    this.autocomplete = new google.maps.places.Autocomplete(input, {});
    google.maps.event.addListener(this.autocomplete, 'place_changed', () => {
      var place: google.maps.places.PlaceResult = this.autocomplete.getPlace();
      this.invokeEvent(place);
    });
  }


回答3:

I solved it this way:

<ion-item>
    <ion-label>Search your city</ion-label>
    <ion-input formControlName="placeAutofill" id="googlePlaces" required></ion-input>
</ion-item>

And in my code:

ionViewWillEnter() {
   // Google Places API auto complete
   let input = document.getElementById('googlePlaces').getElementsByTagName('input')[0];
   let autocomplete = new google.maps.places.Autocomplete(input, {types: ['geocode']});
   google.maps.event.addListener(autocomplete, 'place_changed', () => {
     // retrieve the place object for your use
     let place = autocomplete.getPlace();
   });
}