本文介绍了可以在Angular绑定中使用array.filter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板中有这一行:

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

运行此命令时,出现以下错误:

When I run this, I get the following error:

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

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

Does this mean you can't use array.find from within a binding?

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

I know my objects have values, and the expression evaluates in the watch window.Any suggestions?

虽然这个问题及其答案会解决这个问题,但我认为他们不会是重复的.这个问题是特定于过滤到较小的列表(也许是一条记录)的,因为我的问题是每次都会获得一条记录.在这方面,@ Thierry-Templier的回答看起来不错,而且我喜欢它使html变得干净多了.

While this question and its answer will get around the issue, I don't think they are duplicates. That question is specific to filtering to a smaller list, perhaps one record, where as my problem is getting one record everytime. @Thierry-Templier's answer looks good in this regard, and I like how clean it makes the html.

推荐答案

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

You could also implement a custom pipe:

@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'
        }
      ]
    }
  }
}

查看此插件: https://plnkr.co/edit/D2xSiF?p=preview .

这篇关于可以在Angular绑定中使用array.filter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:01