如何正确地与反应形式进行2合? [英] How to correctly 2-way-bind with reactive forms?
问题描述
到目前为止,我一直看到您不应该将 [(ngModel)]
与反应形式混合使用,而只需使用 formControlName
。
So far I've always seen that you shouldn't mix using [(ngModel)]
with reactive forms, and instead simply use formControlName
.
但是,对我来说,这似乎不起作用?
However, for me it doesn't seem to be working?
我有一个表单,并向其中添加了控件
I have a form and I add controls to it
this.exportForm.addControl("surcharge", new FormControl(this.details.SurchargeExtraField));
,然后在我的html中,输入 formControlName
and in my html I give the input the formControlName
<div class="col-sm-12 col-md-6">
<input type="text" formControlName="surcharge" />
</div>
但是,当我使用输入时,它不会改变 this。 details.SurchargeExtraField
,仅适用于验证。
However when I use the input it doesn't change anything about this.details.SurchargeExtraField
, it only works for validation.
当我这样做时:
<input type="text" formControlName="surcharge" [(ngModel)]="details.SurchargeExtraField" />
它可以很好地工作,但显然不是正确的方法。
It works perfectly, but appareantly it's not the correct way.
推荐答案
您可以听这样的表单更改
You can listen for form changes like this
this.exportForm.valueChanges.subscribe((changes) => {
console.log(changes);
});
或者您可以听这样的formcontrol更改
or you can listen for formcontrol changes like this
this.exportForm.get('surcharge').valueChanges.subscribe((change) => {
console.log(change);
});
或者您可以这样做
onChange (newVal) {
console.log(newVal);
}
<input type="text" formControlName="surcharge" #surchargeInput (change)="onChange(surcharge.target.value)"/>
这篇关于如何正确地与反应形式进行2合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!