[英]Update a field in reactive-forms on valueChanges
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'.
使用我目前的方法,我尝试使用“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
.在另一次尝试中,我尝试使用
pipe
和map
更改值。 In tap
the correct path is then written, but it is not used for the field.然后在
tap
中写入正确的路径,但它不用于该字段。
this.paymentForm
.get('amountFormatted')
.valueChanges.pipe(
map((val) => (val = this.formatAmount(val))),
tap((change) => console.log('onTap', change))
)
.subscribe();
Consider setting emitEvent
to false
as demonstrated below:考虑将
emitEvent
设置为false
,如下所示:
this.paymentForm.get('amountFormatted').valueChanges.subscribe((change) => {
this.paymentForm
.get('amountFormatted')
.setValue(this.formatAmount(change), { emitEvent: false });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.