I am trying to figure out how to use a pipe within a reactive form so that the input is forced into a currency format. I have already created my own pipe for this which I h
I was going to write a custom control, but found that overriding the "onChange" from the FormControl class via ngModelChange
was easier. The emitViewToModelChange: false
is critical during your update logic to avoid recurring loop of change events. All piping to currency happens in the component and you don't have to worry about getting console errors.
@Component({
providers: [CurrencyPipe]
})
export class MyComponent {
form = new FormGroup({
amount: new FormControl('', { validators: Validators.required, updateOn: 'blur' })
});
constructor(private currPipe:CurrencyPipe) {}
onChange(value:string) {
const ctrl = this.form.get('amount') as FormControl;
if(isNaN(value.charAt(0))) {
const val = coerceNumberProperty(value.slice(1, value.length));
ctrl.setValue(this.currPipe.transform(val), { emitEvent: false, emitViewToModelChange: false });
} else {
ctrl.setValue(this.currPipe.transform(value), { emitEvent: false, emitViewToModelChange: false });
}
}
onSubmit() {
const rawValue = this.form.get('amount').value;
// if you need to strip the '$' from your input's value when you save data
const value = rawValue.slice(1, rawValue.length);
// do whatever you need to with your value
}
}