2

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>
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Michael Mitch
  • 403
  • 2
  • 7
  • 17
  • Do you need to have the comma on the form? That's usually a bad idea, for monetary values you should store only the number and use a pipe to show it formatted. You can use the default currency pipe: https://angular.io/api/common/CurrencyPipe – Daniel Grabowski Nov 16 '20 at 14:39
  • `/\D/` matches (and removes) all non-digits. Try `/[^0-9,]/` instead. – rveerd Nov 16 '20 at 15:47

1 Answers1

0

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').
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563