Angular 4 Pipe Filter


Answer :

Here is a working plunkr with a filter and sortBy pipe. https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview

As developer033 mentioned in a comment, you are passing in a single value to the filter pipe, when the filter pipe is expecting an array of values. I would tell the pipe to expect a single value instead of an array

export class FilterPipe implements PipeTransform {     transform(items: any[], term: string): any {         // I am unsure what id is here. did you mean title?         return items.filter(item => item.id.indexOf(term) !== -1);     } } 

I would agree with DeborahK that impure pipes should be avoided for performance reasons. The plunkr includes console logs where you can see how much the impure pipe is called.


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


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable