I have a complicated FormGroup which contains multiple FormControls, FormGroups and FormArrys.
I need to implement form reset to its initial value. However, the initial value may be retrieved from the server. Meaning that I get some kind of JSON then parse it into my FormGroup and I need to save this state to be able to reset everything to what it was before.
FormGroup.reset() or FormGroupDirective.resetForm() just reset the values of controls while not changing the FormArrays length.
I have following structure of 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([])
});
Where each FormArray is filled with complex FormGroups after JSON fetch.
What is the best way to save the initial state and then recover it on form reset?
For now I'm trying to do it that way
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));
});
}
}
However, this approach requires manual FormArray reset to 0 so that no extra values will be present and doesn't seem right.
Approximate 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'
}