角度 6 反应形式上的两种方式绑定 [英] Two way binding on angular 6 reactive form

查看:32
本文介绍了角度 6 反应形式上的两种方式绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个复杂的反应式表单,其中包含填充有数据对象的嵌套组件.

I am trying to create a complex reactive form with nested component that is populated with a data object.

我试图实现的行为与模板驱动表单的双向数据绑定非常相似:当用户编辑表单的输入时,数据对象自动.

The behavior I am trying to achieve is very similar to the two-way data binding of a template-driven form: when the user edits an input of the form, the data object is changing automatically.

但与模板驱动的表单相反,我不能使用 [(ngModel)] 因为它在 angular V6 的反应式表单中已被弃用.

but as opposed to template-driven form, I cannot use [(ngModel)] because it is deprecated in reactive forms for angular V6.

我知道 fromGroup.patchValue() 只会做一种方式绑定,然后我必须手动订阅更改事件并手动更新数据对象 - 这会导致很多累人代码.

I know that fromGroup.patchValue() will only do a one way binding and then ill have to manually subscribe to change events and update the data object manually - this will result in a lot of tiring code.

这种情况有什么解决方法吗?

Is there any workaround for that scenario?

推荐答案

好吧,如果我理解正确的话,我遇到了类似的问题(我真的不知道这是否是最佳实践)但它对我有用,所以在 HTML 中:

Well if I understand you correctly I had a similar problem what I did (I really don't know if this is the best practice)but it's work for me so in the HTML:

<mat-form-field class="mat-container">
    <input matInput  [formControl]="generalDiscount" type="number" 
        formControlName="generalDiscount" 
        (input)="course.amounts.generalDiscount = $event.target.value" <-the workaround 
        placeholder="Discount" required="required">
</mat-form-field>

此输入使其成为双向绑定,并且在您的 .ts 类中,您需要将相同的字段放入表单组中,例如

This input makes it two way binding and in your .ts class you need to put the same field in your form group like

this.amountGroup = this._formBuilder.group({

    [this.course.amounts.fitToNomberOfPeople,Validators.required],
    generalDiscount:[this.course.amounts.generalDiscount,Validators.required],

});

希望能帮到你

这篇关于角度 6 反应形式上的两种方式绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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