Manually trigger pipe update

ncohen picture ncohen · May 5, 2017 · Viewed 11.9k times · Source

I have created a pipe to be able to use *ngFor with objects. However, when the object is updated, the pipe does not update. I have found a solution here by using stateful pipe with pure: false.

This solution is not acceptable in terms of performance for my use case as it will refresh the pipe for each change (I use this pipe almost everywhere to render complex elements).

Is there a way to trigger a manual refresh of the pipe so it refreshes only when I want?

Here is a plunker - to see the problem try to remove a name by clicking a - button. If you add pure:false you will see that it will work:

@Pipe({name: 'keys', pure: false})
export class Keys implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

What I would like is to add something to my delName() function so it updates the pipe...

Answer

Pengyy picture Pengyy · May 5, 2017

One way to make a Pure Pipe becoming impure is add a parameter to your Pipe.

when you want to refresh, just change the parameter.


Another way without parameter:

Pure Pipe will be fired when its input has a new instance. So with TypeScript 2.1+, the below code will copy the original object with a new instance, and lead pure pipe to be fired.

let copy = { ...original }

Both ways are included in stackbliz demo.