【发布时间】:2020-02-01 06:48:58
【问题描述】:
我有很多输入需要验证。所以我使用反应形式来验证它们。 例如,
<input formControlName="testName">
在构造函数中我定义了嵌套表单。
constructor(private fb: FormBuilder) {
this.totalForm = this.fb.group({
'subForm': this.fb.group({
testName: [null, Validators.required]
// ....
})
});
}
当我向服务器提交数据时,我想使用输入字段中的新数据。但是我发现表单控件的数据没有更新。原因是表单不能双向绑定,除非使用ngModel。
this.dataTobeSubmited = this.totalForm.controls['subForm'].controls['testName'].value;
我用的是Angular 5,当然可以加ngModel。但是如果以后我们升级到高版本,就会成为一个问题,因为
在 Angular 6 中不推荐将 Reactive Froms 与 ngModel 一起使用,并且 在角度 7 中删除
我的案例是一个嵌套的响应式表单,有没有更好的方法来做双向绑定?
更新我的绑定
嵌套表单组示例的绑定。
<form [formGroup]="profileForm">
<app-child [subForm]="profileForm.controls['subForm']"></app-child>
<button (click)="whatIsTheFormValue()"> What Is My Value?</button>
</form>
https://stackblitz.com/edit/angular-9dzabi
我说的对吗?
【问题讨论】:
-
一个更完整的例子可以帮助我们缩小问题的范围。另外,为了澄清,您是否正在访问表单组的值(this.totalForm.value),它的值不是最新的?
-
this.totalForm.value.subForm.testName,不,即使在 Angular 6 中也不添加 [(ngModel)]
标签: angular angular-forms