Search code examples
typescriptangular7

How can I flatten a nested formGroups in angular


I have a nested formGroup like this:

 generalFG= new FormGroup({
    firstFG : new FormGroup({
      AA: new FormControl('', [Validators.required]),
      BB: new FormControl('', [Validators.required])
    }),
    secondFG : new FormGroup({
      CC: new FormControl('', [Validators.required,]),
      DD: new FormControl('', [Validators.required,])
     
  });

and I want to flatten them into one fromGroup , This is the desired result:

  generalFG= new FormGroup({
      AA: new FormControl('', [Validators.required]),
      BB: new FormControl('', [Validators.required]),
      CC: new FormControl('', [Validators.required,]),
      DD: new FormControl('', [Validators.required,])     
  });

Solution

  • I wrote like this code and it works nice:

     addControlsRange(formGroupName: string, formJoin: any): any {
        Object.keys(this.generalFG.get(formGroupName).controls).forEach(key => {
          var vRes = this.generalFG.get(formGroupName).controls[key];
          formJoin.addControl(key, vRes);
        });
        return formJoin;
      }
    
      initGeneralFG(): void {
        var formJoin: FormGroup=new FormGroup(this.generalFG.get('firstFG').controls);
        formJoin=this.addControlsRange('secondFG',formJoin);
        formJoin=this.addControlsRange('thirdFG',formJoin);
        this.generalFG = formJoin;
    }