Angular 9, NgModel on text input is resetting when string is "0"

Viewed 175

I have an html input of type text and it's connected by [(ngModel)] to a formattedValue variable which updates whenever a value is entered.

I'm using this input field mainly for displaying numbers and it's of type text because after the user is putting in a number, I want to show it formatted (e.g: 1234 -> 1,234).

The problem occurs when I'm entering the number 0, it converts it to a string "0" and sets the input field value, but the input is always resetting - meaning, its value is being removed and the placeholder is showing.

This is my input:

<input
    class="form-control form-text-input"
    type="text"
    name="field-{{ field.id }}"
    id="field-{{ field.id }}"
    [(ngModel)]="formattedValue"
    (change)="updateFieldValue($event.target)"
    placeholder="Enter any number">

And this is the logic:

formattedValue = '';

updateFieldValue($target: any) {
    const decimalValue = parseFloat($target.value.replace(/,/g, ''));

    if (decimalValue > 999) {
        this.formattedValue = this._getFormattedValue();
    } else {
        this.formattedValue = decimalValue.toString();
    }
}

private _getFormattedValue(): string {
    return DecimalPipe.prototype.transform(this.field.value || this.field.defaultValue, undefined, 'en-US');
}

Here's a GIF showing the issue:

enter image description here

Thanks!

0 Answers
Related