我正在尝试使用填充了数据对象的嵌套组件创建复杂的反应形式。
我想要实现的行为与模板驱动表单的双向数据绑定非常相似:当用户编辑表单的输入时,数据对象正在自动更改 。
但与模板驱动的表单相反,我不能使用[(ngModel)]
,因为它在角度V6的反应形式中已弃用。
我知道fromGroup.patchValue()
只会进行单向绑定,然后不得不手动订阅更改事件并手动更新数据对象 - 这将导致大量疲惫的代码。
该方案是否有解决方法?
答案 0 :(得分:4)
如果我对您的理解正确,我会遇到类似的问题(我确实不知道 知道这是否是最佳做法),但它对我有用,因此在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.amountGroup = this._formBuilder.group({
[this.course.amounts.fitToNomberOfPeople,Validators.required],
generalDiscount:[this.course.amounts.generalDiscount,Validators.required],
});
希望有帮助
答案 1 :(得分:0)
某种解决方法。
命题是使用(输入)事件。 formControl1更新自己的值,并将其值也与其他“ @ example.com”文本一起写入formControl2。更改formControl2的值将更新自己的值,并使用带条纹的'@ example.com'文本更新formControl1。import { Component } from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'app-template-and-reactive-form',
template: '<input #inp1 [ngModel]="formControl1.value" ' +
'(input)="formControl1.setValue(inp1.value);formControl2.setValue(inp1.value+\'@example.com\')" ><br>\n' +
'<input #inp2 [ngModel]="formControl2.value" ' +
'(input)="formControl2.setValue(inp2.value);formControl1.setValue(inp2.value.replace(\'@example.com\',\'\'))"><br>\n' +
'formControl1 value: {{formControl1.value}}<br>\n' +
'formControl2 value: {{formControl2.value}}<br>',
styleUrls: ['./template-and-reactive-form.component.scss']
})
export class TemplateAndReactiveFormComponent {
formControl1 = new FormControl('');
formControl2 = new FormControl('');
}