I have this pipe which multiplies the input value by an other value retrieved from a service:
@Pipe({
name: 'multiply'
})
export class MultiplyPipe implements PipeTransform {
constructor(private service: StateService) { }
transform(value: any, args?: any): any {
return value * this.service.multiplier;
}
}
Usage:
{{ value | multiply }}
DEMO
This works fine, but when the multiply
value from the service is changed, it doesn't trigger any change detection, and thus
{{ value | multiply }}
is not run again, leaving the old value on the screen. Any suggestion how this can be fixed?
Pure Pipes A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe.
To execute a custom pipe after a change within a composite object, such as a change to an element of an array, you need to define your pipe as impure to detect impure changes. Angular executes an impure pipe every time it detects a change with every keystroke or mouse movement.
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.
As discussed in Angular documentation, and as shown in this stackblitz, one way to force the pipe to be called is to make it impure:
@Pipe({
name: 'multiply',
pure: false
})
For more details about pure and impure pipes, you can see this article.
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