如何使用反应形式将表单绑定到Angular 6中的模型



在angular 6之前,我使用[(ngModel)]将表单字段直接绑定到模型。现在已经弃用了(不能与反应式表单一起使用(,我不知道如何使用表单值更新我的模型。我可以使用form.getRawValue(),但这需要我用新的rawValue替换当前模型——这是不好的,因为我的主模型比本地表单模型更大,字段也更多。

有什么想法吗?

不要使用[(ngModel)]!反应形式要好得多。它们使手动ngModel绑定过时,而且它们有一些非常好的内置功能——我将在这个答案中介绍其中的几个。

绑定到表单

如果您绑定到一个表单控件,例如文本输入,请使用以下模板语法:

<ng-container [formGroup]="this.myFormGroup">
<input type="text" formControlName="field1">
<input type="text" formControlName="field2">
<ng-container formGroupName="subgroupName">
<input type="text" formControlName="subfield2">
</ng-container>
<input type="text" formControlName="myRequiredField">
</ng-container>

(field1field2subgroupNamesubfield2myRequiredField都是与表单各部分相对应的任意控件和控件组名称,创建FormGroup对象时请参阅下文。(

关于<ng-container>的注意事项:当然,您也可以使用任何其他标记来代替<ng-container>,如果这更有语义的话。例如<form [formGroup]="this.myFormGroup">。我在这里使用了<ng-container>,因为它在渲染时不会创建额外的HTML元素;CCD_ 15在DOM树中仅作为CCD_。如果你使用依赖于具有特定结构的标签的CSS,那就太好了。

FormGroup模型的只读数据绑定在您的模板中的访问方式略有不同:

{{ this.myFormGroup.get('field1').value }}
{{ this.myFormGroup.get('subgroupName.subfield2').value }}
<!-- Hint: use an array if you have field names that contain "." -->
{{ this.myFormGroup.get(['subgroupName', 'subfield2']).value }}

创建FormGroup

在组件类中,在constructor()中(这应该在模板呈现之前(,使用以下语法构建一个表单组来与此表单对话:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
...
public readonly myFormGroup: FormGroup;
...
constructor(private readonly formBuilder: FormBuilder) {
this.myFormGroup = this.formBuilder.group({
field1: [],
field2: [],
subgroupName: this.formBuilder.group({
subfield2: [],
}),
myRequiredField: ['', Validators.required],
});
this.retrieveData();
}

用数据填写表格

如果您的组件需要在加载时从服务中检索数据,则必须确保它在构建表单后开始传输,然后使用patchValue()将对象中的数据放入FormGroup:

private retrieveData(): void {
this.dataService.getData()
.subscribe((res: SomeDataStructure) => {
// Assuming res has a structure matching the template structure
// above, e.g.:
// res = {
//     field1: "some-string",
//     field2: "other-string",
//     subgroupName: {
//         subfield2: "another-string"
//     },
// }
// Values in res that don't line up to the form structure
// are discarded. You can also pass in your own object you
// construct ad-hoc.
this.myFormGroup.patchValue(res);
});
}

从表单中获取数据

现在,假设您的用户单击提交,现在您需要将数据从表单中取出,并通过服务将其POST返回到API。只需使用getRawValue:

public onClickSubmit(): void {
if (this.myFormGroup.invalid) {
// stop here if it's invalid
alert('Invalid input');
return;
}
this.myDataService.submitUpdate(this.myFormGroup.getRawValue())
.subscribe((): void => {
alert('Saved!');
});
}

所有这些技术都消除了对任何[(ngModel)]绑定的需要,因为表单在FormGroup对象中维护自己的内部模型。

正如Angular文档中更全面地解释的那样,对于反应式表单,您不会将表单直接绑定到您的模型。相反,您使用FormBuilder来构建一个FormGroup对象(本质上是"表单"(,该对象将维护自己的模型。在构造过程中,您有机会在表单中设置初始值,这通常是在您的模型中进行的。

然后将模板中的表单控件绑定到表单的模型。用户与表单控件的交互会更新表单的模型。

当您准备对表单数据进行处理时(例如"提交"表单(,您可以使用FormGroup的value属性或它的getRawValue((方法从表单字段中获取值,这两种方法的行为不同,请参阅文档了解详细信息。

一旦您从表单中获得值,如果您愿意,您可以用表单中的值更新您的模型。

您可以订阅表单组中的更改,并使用它来更新模型。但这并不安全。因为您必须确保表单字段与模型字段匹配,或者添加验证以验证模型中的字段是否存在。

bindModelToForm(model: any, form: FormGroup) {
const keys = Object.keys(form.controls);
keys.forEach(key => {
form.controls[key].valueChanges.subscribe(
(newValue) => {
model[key] = newValue;
}
)
});
}

我的服务的完整代码:
referenceFields-意味着如果你有像student: { name, group }这样的复杂字段,group是一个引用模型,你需要能够从这个模型中只获取id:

import { Injectable } from '@angular/core';
import { FormGroup } from "@angular/forms";
@Injectable({
providedIn: 'root'
})
export class FormService {
constructor() {
}
bindModelToForm(model: any, form: FormGroup, referenceFields: string[] = []) {
if (!this.checkFieldsMatching(model, form)) {
throw new Error('FormService -> bindModelToForm: Model and Form fields is not matching');
}
this.initForm(model, form);
const formKeys = Object.keys(form.controls);
formKeys.forEach(key => {
if (referenceFields.includes(key)) {
form.controls[key].valueChanges.subscribe(
(newValue) => {
model[key] = newValue.id;
}
)
} else {
form.controls[key].valueChanges.subscribe(
(newValue) => {
model[key] = newValue;
}
)
}
});
}
private initForm(model: any, form: FormGroup) {
const keys = Object.keys(form.controls);
keys.forEach(key => {
form.controls[key].setValue(model[key]);
});
}
private checkFieldsMatching(model: any, form: FormGroup): boolean {
const formKeys = Object.keys(form.controls);
const modelKeys = Object.keys(model);
formKeys.forEach(formKey => {
if (!modelKeys.includes(formKey)) {
return false;
}
});
return true;
}
}

最新更新