How to apply filters to *ngFor?

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

    A lot of you have great approaches, but the goal here is to be generic and defined a array pipe that is extremely reusable across all cases in relationship to *ngFor.

    callback.pipe.ts (don't forget to add this to your module's declaration array)

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

    Then in your component, you need to implement a method with the following signuature (item: any) => boolean, in my case for example, I called it filterUser, that filters users' age that are greater than 18 years.

    Your Component

    @Component({
      ....
    })
    export class UsersComponent {
      filterUser(user: IUser) {
        return !user.age >= 18
      }
    }
    

    And last but not least, your html code will look like this:

    Your HTML

  • {{user.name}}
  • As you can see, this Pipe is fairly generic across all array like items that need to be filter via a callback. In mycase, I found it to be very useful for *ngFor like scenarios.

    Hope this helps!!!

    codematrix

提交回复
热议问题