Ionic 2 Searchbar – Searchbar provides search functioinality to the users. A searchbar basically binds a model with input which triggers an event when model is changed. It is very simple to create searchbar in Ionic 2. Here in this tutorial we are going to explain how you can create searchbar in Ionic 2. You can also use our online editor to run and see the output of the example.
Ionic 2 Searchbar | Search Functionality Example
Let us create very basic searchbar –
It contains the following part-
- Html Part
- Controller Part
Now let us go one by one to understand how it works-
Html Part: demo.html
Html part contains the following input elements for searchbar.
Ionic 2 Searchbar | Search Functionality | Example:
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar> <ion-list> <ion-item *ngFor="let item of items"> {{ item }} </ion-item> </ion-list> |
Now let us create the controller part of the above example.
Controller Part: demo.ts
Controller part contains the following script-
Searchbar Controller Example:
import { Component } from '@angular/core'; @Component({ templateUrl: 'demo.html' }) export class DemoPage { items; constructor() { this.initializeItems(); } initializeItems() { this.items = [ 'Google', 'Facebook', 'Microsoft', 'Yahoo', 'IBM', 'Oracle', 'Airtel', 'HCL', 'HP', 'Wipro', 'TCS' ] } getItems(ev) { // Reset items back to all of the items this.initializeItems(); // set val to the value of the ev target var val = ev.target.value; // if the value is an empty string don't filter the items if (val && val.trim() != '') { this.items = this.items.filter((item) => { return (item.toLowerCase().indexOf(val.toLowerCase()) > -1); }) } } } |
If you run the above example it will produce the output something like this-