Reputation: 914
I want to implement search functionalities with ionic2 + angular2. In previous version I used This Filter Example but in newer version this is not working.
How it is work with angular2 + ionic2 ?
Upvotes: 0
Views: 3422
Reputation: 44659
You can use the Searchbar component. Please take a look at this working plunker.
It's pretty easy to use, first in your Component
make sure to have a list of items to show 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);
})
}
}
}
Just like you can see in that code, the magic is being done in these lines of code:
// 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);
})
}
So everytime you type something, we filter the items that contains the what you've typed in the search bar. Then add this code in 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>
Please notice that we're binding the ionInput
event from the ion-searchbar
element to the getItems
method by doing:
(ionInput)="getItems($event)
Upvotes: 3