How to apply filters to *ngFor?

前端 未结 23 1248
無奈伤痛
無奈伤痛 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 04:11

    Simplified way (Used only on small arrays because of performance issues. In large arrays you have to make the filter manually via code):

    See: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

    @Pipe({
        name: 'filter'
    })
    @Injectable()
    export class FilterPipe implements PipeTransform {
        transform(items: any[], field : string, value : string): any[] {  
          if (!items) return [];
          if (!value || value.length == 0) return items;
          return items.filter(it => 
          it[field].toLowerCase().indexOf(value.toLowerCase()) !=-1);
        }
    }
    

    Usage:

  • {{it}}
  • If you use a variable as a second argument, don't use quotes.

提交回复
热议问题