Hi I am using Angular 2 pipe to return the keys of object, it is an impure pipe and It is being executed multiple times which is blocking some other script, how can I avoid multiple executions of the impure pipes? my code is as follows :
import {Pipe,PipeTransform} from '@angular/core';
@Pipe({ name: 'NgforObjPipe', pure: true })
export class NgforObjPipe implements PipeTransform {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
console.log('pipeeeeeeeeeeeeeee', keys);
return keys;
}
}
Impure pipes are required because angular ignores changes to composite objects. Impure pipes execute every time angular detects any changes regardless of the change in the input value. It uses the impure function.
From the above code, the isPure method will check whether a pipe is pure or impure by looking at the pure property in @Pipe decorator. For impure pipes Angular calls the transform method on every change detection. For any input change to the pure pipe, it will call transform function.
Because of the way Promise s work, Angular's async pipe has to be impure (meaning that it can return different outputs without any change in input). The transform method on Pipe s is synchronous, so when an async pipe gets a Promise , the pipe adds a callback to the Promise and returns null.
Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence. Do you have an example?
There is no way to prevent that. That's what an impure pipe is for.
What you can do is, to ensure that as little work is done inside the the transform()
method as possible, for example by caching results and only recalculate when the passed value has actually changed.
You can also use Object.keys()
to get more efficient code.
See also How to iterate [object object] using *ngFor in Angular 2
ChangeDetectionStrategy.OnPush
can be used to reduce the number of times change detection is run, to minimize the number of calls to the pipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With