Here's a version that traverse an arbitrary Form structure and gives you the changed values in a nested Map-like structure. Meaning the returned dirty values will be at the same level as the dirty control.
getDirtyValues(
form: FormGroup | FormArray | FormControl | AbstractControl
): Map<string, any> | any[] | any | undefined {
if (!form.dirty) {
return;
}
if (form instanceof FormControl) {
return form.value;
}
if (form instanceof FormGroup) {
const result = new Map();
for (const [key, control] of Object.entries(form.controls)) {
const nestedResult = this.getDirtyValues(control);
if (nestedResult) {
result.set(key, this.getDirtyValues(control));
}
}
return result;
}
if (form instanceof FormArray) {
const result = new Array();
form.controls.forEach(control => {
const nestedResult = this.getDirtyValues(control);
if (nestedResult) {
result.push(nestedResult);
}
});
return result;
}
throw new Error('Form must be a FromGroup, FormArray or FormControl.');
}