Search code examples
angularform-controlformgroups

How to format data in a FormControl


I am using angular 14 with typed FormGroup. I need to format the input textbox to be currency. Can't figure out how to format the "paymentAmount" field as currency:

<form (ngSubmit)="onSubmitForm()" [formGroup]="paymentFormGroup">
  <div class="table-row">
    <div class="table-cell-label">
      <label for="paymentAmount">Payment Amt:</label
      ><label class="required">*</label>
    </div>
    <div class="table-cell-input">
      <input
        id="paymentAmount"
        type="text"
        formControlName="paymentAmount"
        class="input-text"
        [ngClass]="
          isSubmitted &&
          formControls['paymentAmount'].errors &&
          formControls['paymentAmount'].errors['required']
            ? 'input-required'
            : ''
        "
      />
    </div>
  </div>

And in the ts file:

export interface CustomerPaymentInfo {
  name: string | undefined;
  email?: string | null;
  accountNumber: number | undefined;
  paymentAmount: number | undefined;
  accountBalance: number | undefined;
  newAccountBalance: number | undefined;
}


const info: CustomerPaymentInfo = {
  name: this.paymentFormGroup.value.name,
  email: this.paymentFormGroup.value.email,
  accountNumber: this.paymentFormGroup.value.accountNumber,
  paymentAmount: payment,
  accountBalance: this.getAccountBalance(payment, balance),
  newAccountBalance: this.getNewBalance(payment, balance),
};

Solution

  • If you do not want to use external packages, you can listen to formcontrol valueChanges and use currency pipe to modify the value like this

    constructor(private currencyPipe: CurrencyPipe) { }
    
    ngOnInit() {
    
    const paymentAmountControl = this.paymentFormGroup.get('paymentAmount')
    
        paymentAmountControl.valueChanges.subscribe((val: string) => {
        val = val.replace(/[a-zA-Z$,]/g, '')
    
        paymentAmountControl.setValue(this.currencyPipe.transform(val, 'USD', 'symbol', '1.0-0'), { emitEvent: false })
        })
    }
    

    the regular expression strips alphabets and currency symbols, you will have to modify the regex and the transform argument to support the currency used in your application.