我想直接以反应形式格式化输入的内容(最好在显示之前)。 使用当前的方法,我尝试使用“ valueChanges”订阅该字段。
但这可以理解为递归。每次更改订阅字段中的值时,都会再次调用它。
因此,我的问题是,如何在显示输入之前直接对其进行编辑?
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";
}
}
在另一次尝试中,我尝试使用pipe
和map
来更改值。然后在tap
中写入正确的路径,但该路径未用于该字段。
this.paymentForm
.get('amountFormatted')
.valueChanges.pipe(
map((val) => (val = this.formatAmount(val))),
tap((change) => console.log('onTap', change))
)
.subscribe();
答案 0 :(得分:1)
请考虑将emitEvent
设置为false
,如下所示:
this.paymentForm.get('amountFormatted').valueChanges.subscribe((change) => {
this.paymentForm
.get('amountFormatted')
.setValue(this.formatAmount(change), { emitEvent: false });
});