I want to format the entered content in a reactive-form directly (best before displaying it). With my current approach, I try to subscribe to the field with 'valueChanges'.
But this leads understandably to a recursion. Every time I change the value in the subscribe field, it is called again.
Therefore my question, how can I edit the input directly before it is displayed?
export class NewPaymentComponent implements OnInit {
paymentForm: FormGroup;
constructor() {}
ngOnInit(): void {
this.paymentForm = new FormGroup({
amountFormatted: new FormControl('0.00', Validators.required)
});
this.paymentForm.get('amountFormatted').valueChanges.subscribe((change) => {
this.paymentForm
.get('amountFormatted')
.setValue(this.formatAmount(change));
});
}
formatAmount(input: string): string {
// ... method body omitted
return "changed";
}
}
On another attempt, I tried to change the value with pipe and map. In tap the correct path is then written, but it is not used for the field.
this.paymentForm
.get('amountFormatted')
.valueChanges.pipe(
map((val) => (val = this.formatAmount(val))),
tap((change) => console.log('onTap', change))
)
.subscribe();