我正在尝试构建一个能够生成给定FormGroup
副本的函数。我开始时:
function copyForm(form: FormGroup): FormGroup {
const copy = new FormGroup({});
for (let key of Object.keys(form.value)) {
const control = form.controls[key];
/* Copy the data from the control into a new control */
const copyControl = new FormControl({[key]: control.value});
copy.addControl(key, copyControl);
}
但是,如果有FormArray
或FormGroup
,这不起作用。如果它是递归的,这个可能会起作用,但我无法很好地处理它。
我也试图解决它
function copyForm(form: FormGroup): FormGroup {
const copy = new FormGroup({});
for (let key of Object.keys(form.value)) {
const control = form.controls[key];
const copyControl = new FormControl({...control.value});
copy.addControl(key, copyControl);
}
return copy;
}
但这不适用于双嵌套FormGroups
,任何FormArrays
或常规FormControls
......
我也尝试过:
function copyForm(form: FormGroup): FormGroup {
const copy = new FormGroup(Object.assign({}, form.value));
return copy;
}
但这给了我错误:
ERROR TypeError: control.setParent is not a function
我很难过。
这是我提出的深层复制功能,它还保留了每个AbstractControl的相关验证器/异步验证器功能和禁用状态。
/**
* Deep clones the given AbstractControl, preserving values, validators, async validators, and disabled status.
* @param control AbstractControl
* @returns AbstractControl
*/
export function cloneAbstractControl<T extends AbstractControl>(control: T): T {
let newControl: T;
if (control instanceof FormGroup) {
const formGroup = new FormGroup({}, control.validator, control.asyncValidator);
const controls = control.controls;
Object.keys(controls).forEach(key => {
formGroup.addControl(key, cloneAbstractControl(controls[key]));
})
newControl = formGroup as any;
}
else if (control instanceof FormArray) {
const formArray = new FormArray([], control.validator, control.asyncValidator);
control.controls.forEach(formControl => formArray.push(cloneAbstractControl(formControl)))
newControl = formArray as any;
}
else if (control instanceof FormControl) {
newControl = new FormControl(control.value, control.validator, control.asyncValidator) as any;
}
else {
throw new Error('Error: unexpected control value');
}
if (control.disabled) newControl.disable({emitEvent: false});
return newControl;
}
我就是这样做的:
copyFormControl(control: AbstractControl) {
if (control instanceof FormControl) {
return new FormControl(control.value);
} else if (control instanceof FormGroup) {
const copy = new FormGroup({});
Object.keys(control.getRawValue()).forEach(key => {
copy.addControl(key, copyFormControl(control.controls[key]));
});
return copy;
} else if (control instanceof FormArray) {
const copy = new FormArray([]);
control.controls.forEach(control => {
copy.push(copyFormControl(control));
})
return copy;
}
}
我使用的是getRawValue()
而不是value
,因为value
不会包含禁用的控件。
我个人使用lodash cloneDeep()函数在这里找到:
https://lodash.com/docs/#cloneDeep
我用这种方式:
const newFormGroup: any = _.cloneDeep(myFormGroup);
对于仅包含FormControls的简单FormGroup(即不包含FormGroups或FormArrays):
cloneForm(formGroup: FormGroup){
let x = new FormGroup({});
x.patchValue(formGroup.value);
return x;
}