Angular: Change in Pipe not detected

我与影子孤独终老i 提交于 2019-12-22 04:37:46

问题


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?


回答1:


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.




回答2:


I believe the issue is that while the component receives events if it accesses StateService, the pipe does not.

To fix this, instead change MultiplyPipe to take a multiplier argument, instead of trying to access StateService:

transform(value: any, multiplier: any): any {
  return value * multiplier;
}

Then have hello.component access StateService, and pass in the value of multiplier as an argument to the pipe:

import { Component, Input } from '@angular/core';
import { StateService } from './state.service';

@Component({
  selector: 'hello',
  template: `<h1>Value = {{value | multiply: this.service.multiplier}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  value = 10;

  constructor(private service: StateService) {}

Working example here: DEMO



来源:https://stackoverflow.com/questions/48303252/angular-change-in-pipe-not-detected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!