Search code examples
angularangular2-changedetection

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?


Solution

  • 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.