How to apply filters to *ngFor?

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

    I created the following pipe for getting desired items from a list.

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
    
      transform(items: any[], filter: string): any {
        if(!items || !filter) {
          return items;
        }
        // To search values only of "name" variable of your object(item)
        //return items.filter(item => item.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1);
    
        // To search in values of every variable of your object(item)
        return items.filter(item => JSON.stringify(item).toLowerCase().indexOf(filter.toLowerCase()) !== -1);
      }
    
    }
    

    Lowercase conversion is just to match in case insensitive way. You can use it in your view like this:-

    • {{reward.name}}

提交回复
热议问题