I am using reactive form in my Angular project. And I need to format some of the input to currency format.
I have created a directive of currency Mask, which is similar like Format currency input in angular 2
directive
import { Directive, HostListener, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[formControlName][currencyMask]',
})
export class CurrencyMaskDirective {
@Output() rawChange:EventEmitter<number> = new EventEmitter<number>();
constructor(public ngControl: NgControl) { }
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(event.target.value, true);
}
onInputChange(event, backspace) {
var newVal = (parseInt(event.replace(/[^0-9]/g, ''))).toLocaleString('en-US', { minimumFractionDigits: 0 });
var rawValue = newVal;
if(backspace) {
newVal = newVal.substring(0, newVal.length - 1);
}
if(newVal.length == 0) {
newVal = '';
}
else {
newVal = newVal;
}
this.ngControl.valueAccessor.writeValue(newVal);
rawValue = rawValue.replace(/\,/g, '');
this.rawChange.emit(parseInt(rawValue));
}
}
html code
<div class="input-group">
<input type="text" class="form-control" currencyMask formControlName="money">
</div>
component.ts
this.detail.forEach(data => {
control.push(this.fb.group({
money: [this.currencyTransform(money), [minValue(0)]]
})
})
currencyTransform(val: number) {
return this.decimalPipe.transform(val, '1.0-2');
}
function minValue(min: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
if (c.value !== null && (isNaN(c.value) || c.value <= min)) {
return { 'minValue': true };
}
return null;
};
}
However, I can make input field (for example: 10000) display correctly based on using currency mask(display like 10,000), but it will also trigger my Validation since data has changed to currency format (since now it has changed to 10,000).
What should I do to still save as number(for example: 10000) instead of currency format(10,000)? So it will not trigger my Validation. Or maybe the way I am using is wrong? Then what should I do to have a currency mask in reactive form, but still save as number not formatted data?
I really appreciate it.