2016-08-01 81 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 ...这是工作很好....你真是天才。 –