你能在Angular绑定中使用array.filter吗?

Des*_*ley 3 javascript-databinding angular

我的模板中有这一行:

<span>{{ data.things.find(r => { return r.id == 5 }).description }}</span>
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误:

Parser Error: Bindings cannot contain assignments at column...
Run Code Online (Sandbox Code Playgroud)

这是否意味着您无法array.find在绑定中使用?

我知道我的对象有值,表达式在监视窗口中计算.有什么建议?

编辑:虽然这个问题及其答案将绕过这个问题,但我不认为它们是重复的.这个问题特定于过滤到较小的列表,也许是一条记录,因为我的问题是每次都得到一条记录.@ Thierry-Templier在这方面的答案看起来不错,我喜欢它的html干净程度.

Thi*_*ier 6

您还可以实现自定义管道:

@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);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它:

@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'
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅此plunkr:https://plnkr.co/edit/D2xSiF p = preview .