Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 getting only the dirty values in a controlgroup

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?

like image 290
hY8vVpf3tyR57Xib Avatar asked May 20 '16 09:05

hY8vVpf3tyR57Xib


1 Answers

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

like image 61
Ankit Singh Avatar answered Oct 11 '22 15:10

Ankit Singh