角度为6的反应形式上的双向结合 [英] Two way binding on angular 6 reactive form
问题描述
我正在尝试使用填充有数据对象的嵌套组件创建一个复杂的反应形式.
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)]
,因为对于角度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屋!