不要使用[(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>
(field1、field2、subgroupName、subfield2 和 myRequiredField 都是与您的表单部分相对应的任意控件和控件组名称,请参阅下面的创建 @987654329 @对象。)
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 like:
// 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 对象中维护了自己的内部模型。