如何在 angular 中展平嵌套的 formGroups

How can I flatten a nested formGroups in angular

我有一个这样的嵌套 formGroup:

 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,])
     
  });

我想将它们拼合成一个 fromGroup ,这是想要的结果:

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

我写了这样的代码,效果很好:

 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;
}