Search code examples
angularregexangular-reactive-formscurrency-pipe

Transform an input of reactive Form with CurrencyPipe


I have an input where I need to type a monetary value. This means I need to input a comma "," (EUR). I following Code works fine, but the comma is being ignored, I tried out different expressions but no one is working fine. How can I also allow commas?


  ngOnInit(): void {
    this.addTicketForm.valueChanges.subscribe((form) => {
      if (form.ek) {
        this.addTicketForm.patchValue(
          {
            ek: this.currencyPipe.transform(
              form.ek.replace(/\D/g, '').replace(/^0+/, ''),
              'EUR',
              'symbol',
              '1.0-0',
              'de'
            ),
          },
          { emitEvent: false }
        );
      }
    });
  }
<div class="form-group col-3">
        <label for="ek">EK</label>
        <input id="ek" class="form-control" formControlName="ek" />
      </div>

Solution

  • If you always have integer values with no fractional parts, instead of form.ek.replace(/\D/g, '').replace(/^0+/, ''), you can use

    Number(ek.replace(/\D+/g, '')).toLocaleString('en')
    

    That is

    • Remove all non-digit chars (including commas, dots, etc.) with .replace(/\D+/g, '')
    • Format the number using Number(...).toLocaleString('en').