Angular 2 getting only the dirty values in a contr

2019-02-26 04:49发布

问题:

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?

回答1:

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 => {
                let currentControl = form.controls[key];

                if (currentControl.dirty) {
                    if (currentControl.controls)
                        dirtyValues[key] = this.getDirtyValues(currentControl);
                    else
                        dirtyValues[key] = currentControl.value;
                }
            });

        return dirtyValues;
}


回答2:

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