Creating a simple search page in Ionic 2 application

An ionic search bar can be created to bind to a model so that when ever there is any change in that element will emit an input change. (ionInput) attribute callback will be triggered. In this below example we are going to create a search page to list a list of topics that can be filtered using SearchBar.

demo.PNG

Add the Following line of code in .ts file:

  topics: string[];
 
  generateTopics() {
    this.topics = [
      'Storage in Ionic 2',
      'Ionic 2 - calendar',
      'Creating a Android application using ionic framework.',
      'Identifying app resume event in ionic - android',
      'What is hybrid application and why.?',
      'Procedure to remove back button text',
      'How to reposition ionic tabs on top position.',
      'Override Hardware back button in cordova based application - Ionic',
      'Drupal 8: Enabling Facets for Restful web services',
      'Drupal 8: Get current user session',
      'Drupal 8: Programatically create Add another field - Example',  
    ];
  }
 
  getTopics(ev: any) {
    this.generateTopics();
    let serVal = ev.target.value;
    if (serVal && serVal.trim() != '') {
      this.topics = this.topics.filter((topic) => {
        return (topic.toLowerCase().indexOf(serVal.toLowerCase()) > -1);
      })
    }
  }

Call generateTopics function from constructor:

this.generateTopics();

 

 


Add below code in .html file
  <ion-searchbar (ionInput)="getTopics($event)" [showCancelButton]="shouldShowCancel" (ionCancel)="onCancel($event)"></ion-searchbar>
 
  <ion-list>
    <ion-item *ngFor="let topic of topics">
      {{ topic }}
    </ion-item>
  </ion-list>
Category: