I have a form in Angular 2 that works with a custom ControlGroup. At the moment, when I submit my form, I pass all the data with the following line to my controller.
Declare your form.
this.artistDetailForm= formBuilder.group({......});
Define a function to extract values on submit
// feed me controlGroups
getDirtyValues(cg) {
let dirtyValues = {}; // initialize empty object
Object.keys(cg.controls).forEach((c) => {
let currentControl = cg.find(c);
if(currentControl.dirty){
if(currentControl.controls) //check for nested controlGroups
dirtyValues[c] = getDirtyValues(currentControl); //recursion for nested controlGroups
else
dirtyValues[c] = currentControl.value; //simple control
}
});
return dirtyValues;
}
and then do this
(ngSubmit)="updateArtist(getDirtyValues( artistDetailForm ))"
PLUNKER
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.');
}
With the new changes to the Angular Forms I've slightly modified the accepted answer, so it works. Decided to share if anyone is interested. (using Angular 4+)
getDirtyValues(form: any) {
let dirtyValues = {};
Object.keys(form.controls)
.forEach(key => {
const currentControl = form.controls[key];
if (currentControl.dirty) {
if (currentControl.controls)
dirtyValues[key] = this.getDirtyValues(currentControl);
else
dirtyValues[key] = currentControl.value;
}
});
return dirtyValues;
}