How to apply filters to *ngFor?

前端 未结 23 1275
無奈伤痛
無奈伤痛 2020-11-22 03:44

Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, wit

23条回答
  •  难免孤独
    2020-11-22 03:49

    There is a dynamic filter pipe that I use

    Source data:

    items = [{foo: 'hello world'}, {foo: 'lorem ipsum'}, {foo: 'foo bar'}];
    

    In the template you can dinamically set the filter in any object attr:

  • The pipe:

      import { Pipe, PipeTransform } from '@angular/core';
    
      @Pipe({
        name: 'filter',
      })
      export class FilterPipe implements PipeTransform {
        transform(items: any[], filter: Record): any {
          if (!items || !filter) {
            return items;
          }
    
          const key = Object.keys(filter)[0];
          const value = filter[key];
    
          return items.filter((e) => e[key].indexOf(value) !== -1);
        }
      }
    

    Don't forget to register the pipe in your app.module.ts declarations

提交回复
热议问题