How to apply filters to *ngFor?

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

    Based on the very elegant callback pipe solution proposed above, it is possible to generalize it a bit further by allowing additional filter parameters to be passed along. We then have :

    callback.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'callback',
      pure: false
    })
    export class CallbackPipe implements PipeTransform {
      transform(items: any[], callback: (item: any, callbackArgs?: any[]) => boolean, callbackArgs?: any[]): any {
        if (!items || !callback) {
          return items;
        }
        return items.filter(item => callback(item, callbackArgs));
      }
    }
    

    component

    filterSomething(something: Something, filterArgs: any[]) {
      const firstArg = filterArgs[0];
      const secondArg = filterArgs[1];
      ...
      return ;
    }
    

    html

  • {{s.aProperty}}
提交回复
热议问题