如何访问HTML中的formGroup以传递给动态添加的组件

时间:2017-06-22 05:08:18

标签: angular angular-reactive-forms

我正在使用一些配置创建动态表单

我正在关注Todd Motto的博客 Link

以下是我的表格

它包含嵌套的FormGroups 所以我的配置包含一些部分。 Section包含许多fieldGroup和fieldGroup可以包含多个字段

这些字段是formControl,对此我传递[group](参见ng-container) 到这个组我想传递formGroup。现在我只传递一个字符串

<form
  class="dynamic-form"
  [formGroup]="form"
  (submit)="handleSubmit($event)">

  <md-tab-group>
    <div *ngFor="let section of config.sections" >
      <md-tab label={{section.title}} formGroupName={{section.title}}>
        <div *ngFor="let fieldGroup of section.fieldGroups" >
            <div class="card-block card mb-3" formGroupName={{fieldGroup.name}}>
              <ng-container *ngFor="let field of fieldGroup.fields;" dynamicField [config]="field" [group]="fieldGroup.name">
              </ng-container>
            </div>
        </div>
      </md-tab>
    </div>
  </md-tab-group>
  <button>Submit</button>
</form>

这是我的component.ts

ngOnInit(): void {
  this.form = this.createForm();
  console.log(this.form);
}

 createForm(){
    const group = this.fb.group({});
    this.config.sections.forEach(section=>group.addControl(section.title,this.addFieldGroups(section)));
    return group;
    }



addFieldGroups(section): FormGroup{
    const group = this.fb.group({});
    section.fieldGroups.forEach(fieldGroup=>group.addControl(fieldGroup.name,this.addFieldGroup(fieldGroup)));
    return group;
  }



addFieldGroup(fieldGroup): FormGroup{
    const group = this.fb.group({});
    fieldGroup.fields.forEach(field=>group.addControl(field.name, this.createControl(field)));
    return group;
  }



createControl(config) {
    const { disabled, validation, value } = config;
    return this.fb.control({ disabled, value }, validation);
  }

1 个答案:

答案 0 :(得分:0)

我没有得到任何答案所以这就是我所做的

中的HTML中

[group]="getFormGroup(section.title,fieldGroup.name)"`

所以我调用一个传递字符串的函数

这就是我检索formGroup的方法

getFormGroup(sectionName,fieldGroupName){
    var section = this.myForm.controls[sectionName] as FormGroup;
    var fieldGroup =section.controls[fieldGroupName];
    return fieldGroup;
  }