How to apply filters to *ngFor?

前端 未结 23 1581
無奈伤痛
無奈伤痛 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:09

    This is my code:

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

    Sample:

    LIST = [{id:1,name:'abc'},{id:2,name:'cba'}];
    FilterValue = 1;
    
    
                                  {{listItem .name}}
                              
    

提交回复
热议问题