Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Change in Pipe not detected

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?

like image 528
Jeanluca Scaljeri Avatar asked Jan 17 '18 14:01

Jeanluca Scaljeri


People also ask

Which pipe is called in Angular for every change detection?

Pure Pipes A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe.

How can we execute a custom pipe after a change within a composite object such as a change to an element of an array to detect impure changes?

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.

What does pipe () Do Angular?

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.


1 Answers

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.

like image 113
ConnorsFan Avatar answered Sep 20 '22 14:09

ConnorsFan