【问题标题】:How can I flatten a nested formGroups in angular如何以角度展平嵌套的 formGroups
【发布时间】:2021-12-12 10:35:24
【问题描述】:

我有一个这样的嵌套 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,])     
  });

【问题讨论】:

    标签: typescript angular7


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 2021-12-03
      • 2019-11-19
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      相关资源
      最近更新 更多