Skip to content Skip to sidebar Skip to footer

Angular 2 Filter Pipe

Trying to write a custom pipe to hide some items. import { Pipe } from '@angular/core'; // Tell Angular2 we're creating a Pipe with TypeScript decorators @Pipe({ name: 'showfi

Solution 1:

I'm pretty sure this is because you have an initial value of [] for items. When you then later add items to items, the pipe is not reexecuted.

Adding pure: false should fix it:

@Pipe({
    name: 'showfilter',
    pure: false
})
exportclassShowPipe {
    transform(value) {
        return value.filter(item => {
            return item.visible == true;
        });
    }
}

pure: false has a big performance impact. Such a pipe is called every time change detection runs, which is quite often.

A way to make a pure pipe being called is to actually change the input value.

If you do

this.items = this.items.slice(); // create a copy of the array

every time after items was modified (added/removed) makes Angular recognize the change and re-execute the pipe.

Solution 2:

  • It is not recommended to use impure pipe. I will impact your performance.
  • It will be called even source has not been changed.
  • So the correct alternative to be is change the reference of your returning object.
@Pipe({
    name: 'showfilter'
})

exportclassShowPipe {
    transform(value) {
        value = value.filter(item => {
            return item.visible == true;
        });
     const anotherObject = Object.assign({}, value) // or else can do cloning.return anotherObject 
    }
}

Post a Comment for "Angular 2 Filter Pipe"