Search code examples
ionic-frameworkionic4

How to get input from ion-searchbar?


It is super easy problem but I just can't seem to figure this out (And yes I have read the documentation).

I am trying to get the input user puts in the ion-searchbar (in Ionic v4) after they the press search and put in a const/let.

Mah HTML

<ion-searchbar showCancelButton="focus" class=""></ion-searchbar>

I don't know how I should write the TS for this.

Thanks in advance :{)


Solution

    • Use (search) event to call your function. This event is fired when the user will click on the search button provided by the ion-searchbar.

    • To get the value entered in the searchbar, use $event.target.value which gets the value field of the tag which in this case is <ion-searchbar>

      <ion-searchbar
          showCancelButton 
          searchIcon="search" 
          animated
          cancel-button-icon
          (ionCancel)="hideSearch()"
          (search)="yourSearchFunction($event.target.value)" 
          placeholder="Search Some Values">
      </ion-searchbar>
      

    To listen to changes as user types in the search bar:

        <ion-searchbar
            ... 
            (ionInput)="yourInputChangeFunction($event.detail.value)">
        </ion-searchbar>
    

    Note: On Ionic 6+, (ionInput) strangely emits value on $event.target.value although, their documentation mentions $event.detail