How to use pipes in Angular 5 reactive form input

前端 未结 6 910
醉梦人生
醉梦人生 2020-12-13 01:59

I am trying to figure out how to use a pipe within a reactive form so that the input is forced into a currency format. I have already created my own pipe for this which I h

6条回答
  •  情深已故
    2020-12-13 02:34

    The other answers here didn't work properly for me but I found a way that works very well. You need to apply the pipe transform inside the reactive form valueChanges subscription, but don't emit the event so it doesn't create a recursive loop:

    this.formGroup.valueChanges.subscribe(form => {
      if (form.amount) {
        this.formGroup.patchValue({
          amount: this.currencyMask.transform(form.amount)
        }, {
          emitEvent: false
        });
      }
    });
    

    This also requires that your pipe "unformats" whatever was there, which is usually as simply as something like this inside your pipe's transform function:

    value = value.replace(/\$+/g, '');
    

提交回复
热议问题