如何正确地使用反应形式进行 2 路绑定? [英] How to correctly 2-way-bind with reactive forms?

查看:20
本文介绍了如何正确地使用反应形式进行 2 路绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直认为您不应该将 [(ngModel)] 与响应式表单混合使用,而应简单地使用 formControlName.

但是,对我来说它似乎不起作用?

我有一个表单,我向它添加了控件

this.exportForm.addControl("surcharge", new FormControl(this.details.SurchargeExtraField));

并在我的 html 中输入 formControlName

 

<input type="text" formControlName="surcharge"/>

但是,当我使用输入时,它不会改变关于 this.details.SurchargeExtraField 的任何内容,它仅适用于验证.

当我这样做时:

它工作得很好,但显然这不是正确的方法.

解决方案

你可以像这样监听表单的变化

this.exportForm.valueChanges.subscribe((changes) => {控制台日志(更改);});

或者你可以像这样监听表单控件的变化

this.exportForm.get('surcharge').valueChanges.subscribe((change) => {控制台日志(更改);});

或者你可以这样做

onChange (newVal) {控制台日志(新值);}<input type="text" formControlName="surcharge" #surchargeInput (change)="onChange(surcharge.target.value)"/>

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));

and in my html I give the input the formControlName

    <div class="col-sm-12 col-md-6">
        <input type="text" formControlName="surcharge" />
    </div>

However when I use the input it doesn't change anything about this.details.SurchargeExtraField, it only works for validation.

When I do:

<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);
});

or you can listen for formcontrol changes like this

this.exportForm.get('surcharge').valueChanges.subscribe((change) => {
     console.log(change);
});

or you can do this

onChange (newVal) {
   console.log(newVal);
}

<input type="text" formControlName="surcharge" #surchargeInput (change)="onChange(surcharge.target.value)"/>

这篇关于如何正确地使用反应形式进行 2 路绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆