I have this line in my template:
<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...
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?
Edit: 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);
});
}
}
and use it this way:
@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'
}
]
}
}
}
See this plunkr: https://plnkr.co/edit/D2xSiF?p=preview.