首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在valueChanges上更新reactive-forms中的字段

在valueChanges上更新reactive-forms中的字段
EN

Stack Overflow用户
提问于 2020-09-06 03:32:04
回答 1查看 322关注 0票数 1

我想直接在反应式表单中格式化输入的内容(最好在显示之前)。用我目前的方法,我尝试用'valueChanges‘订阅这个字段。

但这会导致递归,这是可以理解的。每次我更改订阅字段中的值时,都会再次调用它。

因此,我的问题是,如何在显示之前直接编辑输入?

代码语言:javascript
复制
export class NewPaymentComponent implements OnInit {
  paymentForm: FormGroup;

  constructor() {}

  ngOnInit(): void {

    this.paymentForm = new FormGroup({
      amountFormatted: new FormControl('0.00', Validators.required)
    });

    this.paymentForm.get('amountFormatted').valueChanges.subscribe((change) => {
      this.paymentForm
        .get('amountFormatted')
        .setValue(this.formatAmount(change));
    });
  }

  formatAmount(input: string): string {
    // ... method body omitted
    return "changed";
  }

}

在另一次尝试中,我尝试使用pipemap更改该值。在tap中,会写入正确的路径,但不会将其用于字段。

代码语言:javascript
复制
    this.paymentForm
      .get('amountFormatted')
      .valueChanges.pipe(
        map((val) => (val = this.formatAmount(val))),
        tap((change) => console.log('onTap', change))
      )
      .subscribe();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-06 03:37:12

考虑将emitEvent设置为false,如下所示:

代码语言:javascript
复制
this.paymentForm.get('amountFormatted').valueChanges.subscribe((change) => {
  this.paymentForm
    .get('amountFormatted')
    .setValue(this.formatAmount(change), { emitEvent: false });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63757807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档