PIPE 被多次调用,我怎样才能让它只调用一次? [英] PIPE is getting called multiple times, how can I make it called only once?

查看:58
本文介绍了PIPE 被多次调用,我怎样才能让它只调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML : (component.html)

HTML : (component.html)

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

Pipe.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.管道已经很纯了.我想了解我们是否可以在第一次迭代后停止管道.谢谢.

Issue here is that Pipe gets called multiple times. If we send input = 123.45 . The pipe should return 123,45 and stop. But filter again gets called. And again input becomes 123.45. Pipe is pure already. I want to understand if we can stop the pipe after first itteration. Thanks.

推荐答案

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

With default change detection strategy, the function bound to the property (or to a directive) will be triggered for each change detection cycle. This is the reason why it's discouraged to bind functions to properties and directives.

改为调用控制器中的函数,将响应保存到变量并在模板中使用绑定.

Instead invoke the function in the controller, save the response to a variable and use bind it in the template.

控制器 (*.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">

这篇关于PIPE 被多次调用,我怎样才能让它只调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆