2015-12-22 68 views
19

我正在研究如何過濾Angular2中的數據數組。在angular2中過濾數組

我用自定義管道看了一下,但我覺得這不是我正在尋找的東西,因爲它似乎更適合於簡單的表示轉換,而不是過濾大量數據。

陣列被設置列如下:

getLogs(): Array<Logs> { 
     return [ 
      { id: '1', plate: 'plate1', time: 20 }, 
      { id: '1', plate: 'plate2', time: 30 }, 
      { id: '1', plate: 'plate3', time: 30 }, 
      { id: '2', plate: 'plate4', time: 30 }, 
      { id: '2', plate: 'plate5', time: 30 }, 
      { id: '2', plate: 'plate6', time: 30 } 
     ]; 
    } 

我想通過id來過濾此。因此,當我在搜索欄中輸入「1」時,它會更新以顯示相應的值。

如果有如何做到這一點的方法,我很想知道!

回答

32

有沒有辦法做到這一點使用默認的管道。以下是默認支持的管道列表:https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/common_pipes.ts

這就是說,你可以輕鬆地添加一個管這樣的用例:

import {Injectable, Pipe} from 'angular2/core'; 

@Pipe({ 
    name: 'myfilter' 
}) 
@Injectable() 
export class MyFilterPipe implements PipeTransform { 
    transform(items: any[], args: any[]): any { 
     return items.filter(item => item.id.indexOf(args[0]) !== -1); 
    } 
} 

並使用它:

import { MyFilterPipe } from './filter-pipe'; 
(...) 

@Component({ 
    selector: 'my-component', 
    pipes: [ MyFilterPipe ], 
    template: ` 
    <ul> 
     <li *ngFor="#element of (elements | myfilter:'123')">(...)</li> 
    </ul> 
    ` 
}) 

希望它可以幫助你, 蒂埃裏

+0

PipeTransform的實現是做什麼的?我對它的目的有點困惑。 – Witted

+0

事實上,當你想要實現一個管道時,你需要實現這個接口並把你的處理放在'transform'方法中。有關更多詳細信息,請參閱相應文檔:https://angular.io/docs/ts/latest/api/core/PipeTransform-interface.html。它的第一個參數對應於列表本身,第二個參數用於篩選列表中的元素... –

+0

感謝您的解釋。最後一個問題是有可能將(ngf)的元素列表中的* ngFor =「#元素」作爲變量的輸出嗎? – Witted

5

我有一個類似的場景在我的樣本之一

<input "(keyup)="navigate($event)" /> 

<div *ngFor="#row of visibleRows"></div>  

...... 

navigate($event){ 
     this.model.navigate($event.keyCode); 
     this.visibleRows = this.getVisibleRows(); 
} 

getVisibleRows(){ 
    return this.model.rows.filter((row) => row.rowIndex >= this.model.start && row.rowIndex < this.model.end); 
} 

我的做法是重新計算上的一些資格賽的陣列。在我的情況下,它是keyup。綁定到函數或過濾器似乎很方便,但建議直接綁定到數組。這是因爲更改跟蹤會被混淆,因爲每次觸發更改跟蹤時,函數/過濾器都會返回一個新的數組實例 - 無論觸發它的是什麼。

下面是完整的源代碼:https://github.com/thelgevold/angular-2-samples/tree/master/components/spreadsheet

我也有一個演示:http://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

+0

伊夫居然發現你的GitHub非常有幫助,所以謝謝你!我的工作表格在很大程度上基於您的網格,使用: 將數組構建到表格中。它是一個新的和稀少文件記錄語言的巨大幫助。這與問題沒有多大關係,但更多的是個人感謝。 – Witted

+0

謝謝!我很高興你發現樣本有幫助 – TGH

+0

「更改跟蹤會變得混亂,因爲每次觸發更改跟蹤時,函數/過濾器都會返回一個新的數組實例」 - 非常正確,但是如果每次都返回相同的數組實例,你使用有狀態的管道。或者,如果你的組件允許,你可以使用'onPush'變化檢測策略與有狀態管道一起使用。我在[This SO answer](http://stackoverflow.com/a/34497504/215945)中討論了這兩個選項。 –