I am trying to create an input component with reactive form that only accepts number. I want the output to be with decimals. I added the pipeline on the value property and also created a directive to transform values that already have decimals back to numbers. The problem i have is that on init of the component, the control has a starting value, the output is shown without decimals. When i enter any number the decimals will appear correctly.
The template
<input inputWithComma
[value]="control.value | number"
[formControl]="control">
The component
@Input() control: FormControl = new FormControl();
constructor() { }
ngOnInit(): void {
}
The directive
@Directive({
selector: '[inputWithComma]',
providers: [DecimalPipe]
})
export class NumberCommaDirective implements OnInit, OnDestroy {
private subscription: Subscription = new Subscription;
constructor(private ngControl: NgControl, private decimal: DecimalPipe) {
}
ngOnInit() {
const control = this.ngControl.control;
this.subscription = control!.valueChanges.pipe(
map(value => {
if (isNaN(Number(value))) {
value = value.replace(/[A-Za-z!@#$%^&*(),]/g, '');
}
return parseInt(value);
})
).subscribe(v => {
if (v) {
control!.setValue(v, { emitEvent: false })
}
});
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}