'Format number input with Angular
In Angular, how would I format the displayed input's value without changing my model value? The value must be displayed with thousand separator (' ' for FR, and ',' for EN) and with decimal separator (',' for FR and '.' for EN).
The input must be formatted when the value is initialized from data load by the backend.
I've tried something like this:
<input class="form-control" name="test"
[ngModel]="mynumberValue"
(ngModelChange)="mynumberValue=$event"
(blur)="someCalculs()"
required
NumberFormat
>
with a directive :
@Directive({ selector: '[NumberFormat]' }) export class NumberDirective implements DoCheck {
private el: HTMLInputElement;
private onLoadCheck = false;
constructor(
private elementRef: ElementRef,
private numberPipe: NumberPipe
) {
this.el = this.elementRef.nativeElement;
}
ngDoCheck() {
// check if value is applied on init
if (this.el.value) {
if (!this.onLoadCheck) {
this.el.value = this.numberPipe.transform(this.el.value);
this.onLoadCheck = true;
}
}
}
@HostListener('blur', ['$event.target.value'])
onBlur(value) {
this.el.value = this.numberPipe.transform(value);
}
@HostListener('focus', ['$event.target.value'])
onFocus(value) {
this.el.value = this.numberPipe.parseToNumber(value);
}
}
And a Pipe :
@Pipe({
name: 'number',
pure: true
})
export class NumberPipe implements PipeTransform {
@SessionStorage('user')
currentUser: User;
transform(input: any, minPrecision = 2, maxPrecision = 5): string {
if (isNaN(input) || input === null) {
return 'N/A';
}
return new Intl.NumberFormat(this.currentUser.langKey, {
minimumFractionDigits: minPrecision,
maximumFractionDigits: maxPrecision
}).format(input);
}
parseToNumber(input: string) {
if (this.currentUser.langKey === 'fr') {
return input.replace(' ', '').replace(',', '.');
}
return input.replace(',', '');
}
}
But with this solution, my model is not recognized like a number.
Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
