Angular 2 getting only the dirty values in a controlgroup

后端 未结 3 1524
清酒与你
清酒与你 2021-01-19 06:13

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.

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-19 06:53

    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

提交回复
热议问题