我的场是有Angular 的,在我的场被直接绑定到[(ngModel)]
之前.现在已经弃用了(不能用于被动表单),我不知道如何用表单值更新我的模型.我可以使用form.getRawValue()
,但这需要我用新的rawValue替换当前模型——这是不可取的,因为我的主模型比本地表单模型更大,字段更多.
有什么 idea 吗?
我的场是有Angular 的,在我的场被直接绑定到[(ngModel)]
之前.现在已经弃用了(不能用于被动表单),我不知道如何用表单值更新我的模型.我可以使用form.getRawValue()
,但这需要我用新的rawValue替换当前模型——这是不可取的,因为我的主模型比本地表单模型更大,字段更多.
有什么 idea 吗?
不要用[(ngModel)]
!react 型更好.它们使手动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>
(100, 101, 102, 103, and 104 are all arbitrary control and control group names that correspond to parts of your form, see below when creating the 105 object.)
在模板中,对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);
});
}
现在,假设你的用户点击提交,现在你需要把数据从你的表单中取出来,并通过一个服务将其返回给你的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
对象中维护自己的内部模型.