0

I have a form input of type number that I would like to add commas in the correct places as I type.

This is my form control along with the conversion code

<ion-input formControlName="minValue" name="minValue" type="number" inputmode="numeric" (input)="convertInput($event)" ></ion-input>



convertInput(event) {
    let amountEntered = event.target.value;
    if (amountEntered) {
      console.log("Value received", amountEntered);
      let convertedValue = amountEntered.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      console.log("converted", convertedValue);
      this.searchForm.controls['minValue'].setValue(convertedValue);
    }
  }

I am able to see the commas in the console but once the control is to be updated with the number containing the comma it throws an error, empties the textbox and starts over

Console log

I don't want to put the type as text as this would allow for letters to be written in the box. However, I've tried using text, but this ends up being the result seen in the screenshot.

If it is a must that I use text how would I restrict text from being entered?

<ion-input formControlName="minValue" name="minValue" type="text (input)="convertInput($event)" ></ion-input> 

console with type text

A.Mac
  • 203
  • 3
  • 19

1 Answers1

0

You need to use a Pipe. Read the answers of this question and your solution must be there.

Add Comma Separated Thousands to Number Inputs in Angular2

Jose Vicente
  • 169
  • 8