2016-03-14 79 views
3

我有這條線在我的模板:你可以在角度綁定中使用array.filter嗎?

<span>{{ data.things.find(r => { return r.id == 5 }).description }}</span> 

當我運行它,我得到以下錯誤:

Parser Error: Bindings cannot contain assignments at column... 

這是否意味着你不能在綁定使用array.find而來?

我知道我的對象有值,表達式在觀察窗口中計算。 有什麼建議嗎?

編輯: 雖然this question及其答案將解決這個問題,我不認爲他們是重複的。這個問題特定於篩選到一個較小的列表,也許是一個記錄,因爲我的問題每次都得到一條記錄。 @ Thierry-Templier的回答在這方面看起來不錯,我喜歡它如何清潔html。

+0

[angular 2 sort and filter]可能的重複(http://stackoverflow.com/questions/32882013/angular-2-sort-and-filter) –

回答

5

你也可以實現自定義管道:

@Pipe({ 
    name: 'filterBy' 
}) 
export class FilterPipe { 
    transform(value: [], args: string[]) : any { 
    let fieldName = args[0]; 
    let fieldValue = args[1]; 
    return value.filter((e) => { 
     return (e[fieldName] == fieldValue); 
    }); 
    } 
} 

,並使用這種方式:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <span>{{(data.thing | filterBy:'id':'5') | json}}</span> 
    `, 
    pipes: [ FilterPipe ] 
}) 
export class AppComponent { 
    constructor() { 
    this.data = { 
     thing: [ 
     { 
      id: 4, 
      description: 'desc1' 
     }, 
     { 
      id: 5, 
      description: 'desc3' 
     } 
     ] 
    } 
    } 
} 

看到這個plunkr:https://plnkr.co/edit/D2xSiF?p=preview

1

如果您正在使用的角度2.(你沒有爲這兩個版本中提到您正在使用的角度版本,並添加標籤): 我不知道它的最佳途徑,但這應該工作:

角-2

<span *ngFor="#thing of data.things"> 
    <span *ngIf="thing.id == 5">{{thing.description}}</span> 
</span> 

角-1:同樣的邏輯,只是改變了語法

+0

謝謝,我正在使用Angular2。這應該工作,我希望有一個更簡潔的寫作方式。 –

+0

你可以創建一個自定義過濾器管道http://stackoverflow.com/questions/32882013/angular-2-sort-and-filter –

相關問題