【问题标题】:PIPE is getting called multiple times, how can I make it called only once?PIPE被多次调用,我怎样才能让它只被调用一次?
【发布时间】:2021-03-19 11:41:43
【问题描述】:

HTML : (component.html)

<input #CostInput class="form-element" formControlName="cost" [value]="replaceDecimal.transform(FormGroup.get('cost').value)">

管道.ts:

commaLocaleCodes = ['AM', 'AR'];
transform(input) {
        if (input) {
            const uiLanguage = 'am');
            if (this.commaLocaleCodes.indexOf(uiLanguage.toUpperCase()) > -1) {
                return input.replace(".", ",");
            } else {
                return input.replace(",", ".");
            }
        }
    }

这里的问题是 Pipe 被多次调用。如果我们发送 input = 123.45 。管道应返回 123,45 并停止。但是过滤器再次被调用。再次输入变为 123.45。

管道已经很纯净了。我想了解我们是否可以在第一次迭代后停止管道。谢谢。

【问题讨论】:

  • 我很确定每次 UI 摘要循环刷新时都会调用管道。如果你想调用一次;您必须在组件代码中这样做并存储该值。当然,以后对输入的任何更改都不会反映在管道上。

标签: javascript angular pipe angular-pipe


【解决方案1】:

使用默认的变更检测策略,绑定到属性(或指令)的函数将在每个变更检测周期被触发。这就是不鼓励将函数绑定到属性和指令的原因。

而是调用控制器中的函数,将响应保存到变量并在模板中使用绑定它。

控制器 (*.ts)

export class SomeComponent implements OnInit {
  transformedValue: any;

  ngOnInit() {
    this.transformedValue = this.replaceDecimal.transform(FormGroup.get('cost').value);
  }
}

模板 (*.html)

<input #CostInput class="form-element" formControlName="cost" [value]="transformedValue">

【讨论】:

  • 试过 pure = true ,没用。不得不采用上述方法。工作!谢谢!
  • @Michael D,拜托,你能做一个stackblitz吗?真的,将[value] 和formControlName 一起使用听起来很奇怪。我使用模糊和焦点解决了这个问题,但我对你的代码很感兴趣
猜你喜欢
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 2022-06-15
  • 2022-12-20
  • 2020-11-28
  • 1970-01-01
相关资源
最近更新 更多