【发布时间】:2019-06-22 08:26:05
【问题描述】:
我有一个复杂的 FormGroup,其中包含多个 FormControls、FormGroups 和 FormArrys。
我需要将表单重置为其初始值。但是,可以从服务器检索初始值。这意味着我得到某种 JSON,然后将其解析到我的 FormGroup 中,我需要保存此状态才能将所有内容重置为之前的状态。
FormGroup.reset() 或 FormGroupDirective.resetForm() 只是重置控件的值,而不改变 FormArrays 的长度。
我有以下 FormGroup 结构
formGroup: FormGroup = this.fb.group({
unitNames: this.fb.array([this.createName()], Validators.required),
types: this.fb.array([], Validators.required),
addresses: this.fb.array([]),
requisites: this.fb.array([]),
note: [null],
mediaContent: this.fb.array([])
});
每个 FormArray 在 JSON 提取后填充有复杂的 FormGroups。
保存初始状态然后在表单重置时恢复它的最佳方法是什么?
现在我正在尝试这样做
resetForm() {
this.formGroupDirective.resetForm();
this.formGroup = this.fb.group({
unitNames: this.fb.array([this.createName()], Validators.required),
types: this.fb.array([], Validators.required),
addresses: this.fb.array([]),
requisites: this.fb.array([]),
note: [null],
mediaContent: this.fb.array([])
});
this.patchDeep(this.savedUnit);
this.resetPopup.close();
}
patchDeep(unit) {
if (unit.unitNames && unit.unitNames.length > 0) {
unit.unitNames.forEach((unitName, i) => {
this.names.setControl(i, this.createName(unitName));
});
}
if (unit.unitAddresses && unit.unitAddresses.length > 0) {
unit.unitAddresses.forEach((addressGroup, i) => {
this.addresses.setControl(i, this.fs.createAddress(addressGroup));
});
}
}
但是,这种方法需要手动将 FormArray 重置为 0,这样就不会出现额外的值并且看起来不正确。
近似 JSON
{
unitNames: [
{
id: 1,
nameTypeId: 3,
value: 'Unit 1'
},
{
id: 2,
nameTypeId: 1,
value: 'Unit Alias'
}
],
types: [
{
unitTypeId: 3,
unitCode: 3131,
unitNote: 'sample text'
}
],
requisites: [
{
country: 'UK',
city: 'London',
build: 'B122/1',
phones: [
{
phoneType: 32,
value: '992-123-1'
},
{
phoneType: 1,
value: '123'
}
]
}
],
note: 'Hello world'
}
【问题讨论】:
-
在
resetForm之后重用“从服务器检索值”时使用的逻辑 -
我现在可以了,但我觉得还有另一种更好的方法。因为我必须从头开始创建我的 formGroup 以不手动遍历所有 FormArrays 导致需要重新创建引用的原因(我将对表单对象的引用存储在其他地方以便于访问。此引用在 formGroup 重新创建期间丢失)
-
你能提供你的json对象吗?
-
@AmiVyas 添加。这是一个近似结构,但它具有真实结构的所有属性。等于 FormControl 的简单键值对。 FormGroup 中的 FormArray。
标签: angular angular-reactive-forms