Angular 4 Pipe Filter

后端 未结 4 1100
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 08:30

I am trying to use a custom pipe to filter my *ngFor loop using an input field with ngModel. With my other custom pipe (sortBy), it works perfectly fine. Howeve

4条回答
  •  孤独总比滥情好
    2020-11-28 09:25

    The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:

    export class FilterPipe implements PipeTransform {
        transform(items: any[], filterBy: string): any {
            return items.filter(item => item.id.indexOf(filterBy) !== -1);
        }
    }
    

    And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:

    export class ProductFilterPipe implements PipeTransform {
    
        transform(value: IProduct[], filterBy: string): IProduct[] {
            filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
            return filterBy ? value.filter((product: IProduct) =>
                product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
        }
    }
    

    And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

提交回复
热议问题