2016-08-01 63 views

回答

3

您可以使用Searchbar component。請看看這個working plunker

這很容易使用,首先在你的Component確保有一個項目列表顯示在視圖中。

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); 
     }) 
    } 
    } 
} 

就像你可以看到代碼,神奇的是正在這些代碼行完成:

// 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); 
    }) 
} 

所以每次你輸入的時候,我們篩選的項目包含了你」已經在搜索欄中輸入。然後在您的視圖添加以下代碼:

<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> 

請注意,我們正在做結合從ion-searchbar元素的getItems方法ionInput事件:

(ionInput)="getItems($event) 
+1

感謝名單@sebaferreras ...這是工作很好....你真是天才。 –