I am trying to format a number input so that I am able to display trailing zeros when necessary which is not possible by default. So I tried to overwrite the [ngModel] binding with a function according to this question and ended up with something like this:
<input type="number" [ngModel]="fmtNum(value)" (ngModelChange)="value = $event">
The function simply converts value
to a formatted string:
fmtNum(value: number): number|string {
return formatNumber(value, 'en', '1.2-2');
}
This in fact works pretty well and the value is displayed correctly (e.g. 0 => "0,00", with comma due to a non-English locale). Unfortunately the page starts getting sluggish, and I found out, that the formatting function is called basically all the time.
Is there a way to prevent the function from being called over and over again? Shouldn't Angular only call the function when the input data changes (similar to pure pipes)? Is there another way to achieve the formatting?
this try :
<input [(ngModel)]="value | formatNumber:'en':'1.2-2'"
(ngModelChange)="value=$event" name="inputField" type="number" />
or if you just want it based on an event
in html
<input [(ngModel)]="numberValue"
(keyup)="fmtNum($event)" name="inputField" type="number" />
in component
numberValue = null;
public fmtNum(e: any): void {
if (e && e != '')
this.numberValue = formatNumber(e.target.value, 'en', '1.2-2');
}