Can you use array.filter in an Angular binding?

ⅰ亾dé卋堺 提交于 2019-12-01 20:47:08

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!