How to use autocomplete on search bar on Ionic 4?

M. Mariscal picture M. Mariscal · Mar 5, 2019 · Viewed 23.2k times · Source

I'm looking for some example but cannot see anyone googling it, just what i want is to hardcode 2 or 3 words, thank you so much. Do i have to look for on ionic 3? or in angular2 better?

Answer

Mohan Gopi picture Mohan Gopi · Mar 5, 2019

In your html file:

     <ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
     <ion-list *ngIf="isItemAvailable">
         <ion-item *ngFor="let item of items">{{ item }}</ion-item>
     </ion-list>

in your ts file:

     // Declare the variable (in this case and initialize it with false)
     isItemAvailable = false;
     items = [];

     initializeItems(){
         this.items = ["Ram","gopi", "dravid"];
     }

     getItems(ev: any) {
         // Reset items back to all of the items
         this.initializeItems();

         // set val to the value of the searchbar
         const val = ev.target.value;

         // if the value is an empty string don't filter the items
         if (val && val.trim() !== '') {
             this.isItemAvailable = true;
             this.items = this.items.filter((item) => {
                 return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
             })
         } else {
             this.isItemAvailable = false;
         }
     }