5

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.

1

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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); }); } }```
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

2 Comments

Thanks, I'm using Angular2. That should work, I was hope there is a more succinct way of writing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.