2016-06-16 88 views
2

我試圖在angular2過濾器,我做的產品是這樣一個數組:angular2過濾問題

private products = ["Apple", "Banana", "Orange"];

,這裏是我的管道過濾器:

import {Pipe} from 'angular2/core'; 

@Pipe({name:'filter'}) 

export class FilterPipe { 
    transform(value, args) { 
     if(!args[0]){ 
      return value; 
     } 
     else if (value) { 
      return value.filter(item => { 
       for (let key in item){ 
        if((typeof item[key]==='string' || item[key] instanceof String) && (item[key].indexOf(args[0]) !== -1)){ 
         return true; 
        } 
       } 
      }); 
     } 
    } 
} 

在我組件我添加了一個ul元素來顯示產品,以及一個input元素來過濾它們:

<input type="text" [(ngModel)]="filterText"> 
       <ul> 
        <li *ngFor="#product of products | filter: filterText"> 
         {{product}} 
        </li> 
       </ul> 

運行此代碼時的問題是,它只能在輸入第一個字母時起作用(過濾),再輸入一個字母就不會起作用。任何幫助?

回答

2

你想字符串的每個字符數組從以輸入的文本

'A' => ('Apple') => 'A'.indexOf('A') 'p'.indexOf('A') ... 
'Ap' => ('Apple') => 'A'.indexOf('Ap') 'p'.indexOf('Ap') ... - always false 
'App' => ('Apple') => 'A'.indexOf('App') 'p'.indexOf('App') ... - always false 

比較我會改變下列管:

@Pipe({name:'filter'}) 
export class FilterPipe { 
    transform(value, args) { 
    if(!args[0]) return value; 
    return value.filter(item => item.indexOf(args[0]) > -1); 
    } 
} 

https://plnkr.co/edit/TpJ6Zu8QovWINqx04KUY?p=preview

! !這是角2測試版


角RC版本的代碼如下:

@Pipe({ name: 'filter' }) 
export class FilterPipe { 
    transform(value, term) { 
    if (!term) return value; 
    return value.filter(item => item.indexOf(term) > -1); 
    } 
} 
+0

現在我看到這個問題,非常感謝,也與我的過濾代碼,我改變了數組來對象和它的作品 –