Angular currency editor

3.9k views Asked by At

I need to make a form control in Angular that supports editing currency values with negative number support and full keyboard support so the user can tab between inputs, type a negative symbol and then enter the value. I have tried ngx-currency, PrimeNG input number and ngx-mask but cannot get exactly what I need.

Here is a StackBlitz of what I have so far.

ngx-currency

<input currencyMask [(ngModel)]="value">

PrimeNG Input Number

<p-inputNumber [(ngModel)]="value" mode="currency"
  currency="USD" locale="en-US"></p-inputNumber>

ngx-mask

<input [(ngModel)]="value" mask="separator" thousandSeparator=","
  prefix="$" [allowNegativeNumbers]="true">

ngx-currency

you need to type the negative symbol after you have typed the value which is kind of counter intuitive and as soon as you type the negative symbol the cursor goes to the end of the input.

PrimeNG

when you type the negative symbol the next number causes the cursor to jump behind the the cents at the end making it completely unusable.

ngx-mask

It's usable but I can't figure out how to get the cents to always be 2 decimal places and the minus symbol is after the $ symbol instead of before the $. It is the closest as it is usable but the value showing as $50.5 instead of $50.50 will get it rejected by my product owner.

The control will be used in a spreadsheet style page where tabbing between inputs and entering in the characters -50.50 needs to cause the value to be negative $50 and 50 cents.

2

There are 2 answers

3
Sergey On

Not clear what problem you have with ngx-mask. I've created a sample https://stackblitz.com/edit/angular-ivy-rz1dkp?file=src%2Fapp%2Fapp.component.html

It doesn't put the minus before the $. What of the "always" have 2 digits in cents is up to your formatting.

I've achieved 2 digits in the result by using toFixed(2).

So basically you need to transform the output value when the value is printed/submitted. If you were to change have these cents always have 2 digits in user input it might create a bad UX as thing would "jump"

0
Antikhippe On

It's quite surprising you can't do such a basic thing with three different libraries...

I'm facing the same issues as you even after reading the docs and tried some tests and I'm curious to see a good answer to your question.

While waiting for that, what you could do is to cheat on the prefix with ngx-currency. If the user types minus sign, then update the prefix from '$' to '-$':

HTML

<input [(ngModel)]="value" mask="separator.2" thousandSeparator="," [prefix]="prefix" [allowNegativeNumbers]="false" (keyup)="updatePrefix($event)">

TS

updatePrefix(event: any) {
    if (event.key === "-") {
        this.prefix = this.prefix === "$" ? "-$" : "$";
    }
}

Check demo