3

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.

Community
  • 1
  • 1
Des Horsley
  • 1,759
  • 16
  • 39

2 Answers2

6

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.

Thierry Templier
  • 182,931
  • 35
  • 372
  • 339
  • Slight modification for *at least* angular 7: ``` import { Pipe, PipeTransform } from '@angular/core' @Pipe({ name: 'filterBy' }) export class FilterPipe implements PipeTransform { transform(value: [], fieldName: string, fieldValue: string): any { // console.log('filter args: ', args) // let fieldName = args[0]; // let fieldValue = args[1]; console.log('FILTER: ', fieldName, fieldValue) return value.filter((e) => { return (e[fieldName] == fieldValue); }); } }``` – Jackson Vaughan Nov 08 '19 at 20:23
1

If you are using angular 2. (you didn't mentioned the angular version you are using, and added tags for both version): I don't know if its the best way, but this should work:

Angular -2

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

Angular -1 : Same logic, just change the syntax

manish
  • 828
  • 8
  • 30