Home > other >  How to format data in a FormControl
How to format data in a FormControl

Time:09-05

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 >
    <div >
      <label for="paymentAmount">Payment Amt:</label
      ><label >*</label>
    </div>
    <div >
      <input
        id="paymentAmount"
        type="text"
        formControlName="paymentAmount"
        
        [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),
};

CodePudding user response:

Angular doesn't have a built-in currency formatter. You need to implement custom logic or use some library like ngx-mask

CodePudding user response:

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() {
    this.paymentAmount.valueChanges.subscribe((val: string) => {
    val = val.replace(/[a-zA-Z$,]/g, '')

    this.control.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.

  • Related