gpt4 book ai didi

angular - 你能在 Angular 绑定(bind)中使用 array.filter 吗?

转载 作者:太空狗 更新时间:2023-10-29 18:14:23 24 4
gpt4 key购买 nike

我的模板中有这一行:

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

当我运行它时,出现以下错误:

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

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

我知道我的对象有值,表达式在监 window 口中计算。有什么建议吗?

编辑:同时this question它的答案将解决这个问题,我不认为它们是重复的。该问题特定于过滤到较小的列表,也许是一条记录,而我的问题是每次都获得一条记录。 @Thierry-Templier 的回答在这方面看起来不错,我喜欢它使 html 变得多么干净。

最佳答案

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

@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 - 你能在 Angular 绑定(bind)中使用 array.filter 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com