If you're looking to implement a search feature in your Ionic 2 application, the Searchbar component is the way to go. For a demonstration, check out this working plunker.
Using the Searchbar component is straightforward. Start by ensuring that your Component
has a list of items to display in the view.
import { Component } from "@angular/core";
import { NavController } from 'ionic-angular/index';
@Component({
templateUrl:"home.html"
})
export class HomePage {
constructor() {
this.initializeItems();
}
initializeItems() {
this.items = [
'Amsterdam',
'Bogota',
'Buenos Aires',
'Dhaka'
];
}
getItems(ev) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
let 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);
})
}
}
}
As shown in the code snippet above, the filtering functionality happens within these lines:
// 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);
})
}
To complete the implementation, add the following code snippet to your view:
<ion-header>
<ion-navbar primary>
<ion-title>
Ionic 2
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
Note how we bind the ionInput
event from the ion-searchbar
element to the getItems
method like so:
(ionInput)="getItems($event)