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.
(ngSubmit)="updateArtist(artistDetailForm.value)"
The problem is that this passes all values of a form, and if my forms are quite large this feels quite useless. Is there a possibility to only pass the modified (dirty?) values?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With