Ionic-framework: SearchBar component API method to get the inner input element

Created on 7 Jul 2016  路  4Comments  路  Source: ionic-team/ionic-framework

We need a way to get the HTMLInputElement from the SearchBar component to use it with tools like google.maps.places.Autocomplete, as shown here:
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

autocomplete = new google.maps.places.Autocomplete(
      /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
      {types: ['geocode']});

I had to workaround this issue getting the input by class name:
https://forum.ionicframework.com/t/use-viewchild-on-directives-child/55659

let elem = <HTMLInputElement>document.getElementsByClassName("searchbar-input")[0];
// then
let places = google.maps.places.Autocomplete(elem);

but it would be ideal if the API let us access the input element in some way.
Thanks in advance!
cc @brandyscarney

Most helpful comment

An alternative way to do this is by grabbing the @ViewChild and using querySelector:

<ion-searchbar #searchbar></ion-searchbar>
@Component({
  ...
})
export class SchedulePage {
  @ViewChild('searchbar', {read: ElementRef}) searchbar: ElementRef;

  ngAfterViewInit() {
    var searchInput = this.searchbar.nativeElement.querySelector('.searchbar-input');
    console.log("Search input", searchInput);
  }

}

I'm going to keep this issue open to discuss.

All 4 comments

An alternative way to do this is by grabbing the @ViewChild and using querySelector:

<ion-searchbar #searchbar></ion-searchbar>
@Component({
  ...
})
export class SchedulePage {
  @ViewChild('searchbar', {read: ElementRef}) searchbar: ElementRef;

  ngAfterViewInit() {
    var searchInput = this.searchbar.nativeElement.querySelector('.searchbar-input');
    console.log("Search input", searchInput);
  }

}

I'm going to keep this issue open to discuss.

Yep, it seems to work nicely :D
a little question: ionViewLoaded is equivalent to ngAfterViewInit?
I will share this solution on the forum thread using ionViewLoaded and I wonder if it's ok to handle stuff like google Places or even Maps.

Hello @brandyscarney, do we have news about this issue ?

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SebastianGiro picture SebastianGiro  路  3Comments

Nick-The-Uncharted picture Nick-The-Uncharted  路  3Comments

daveshirman picture daveshirman  路  3Comments

brandyscarney picture brandyscarney  路  3Comments

giammaleoni picture giammaleoni  路  3Comments