How to access a formGroup in HTML to pass to a com

2019-08-03 19:03发布

问题:

I am creating a dynamic form using some configuration

i am following a blog by Todd Motto Link

Following is my form

It contains nested FormGroups so my config contain a number of section. Section contains a number of fieldGroup and fieldGroup can contain a number of fields

these fields are formControl, to this i am passing [group] (see ng-container) to this group i want to pass formGroup. Right now i am passing just a string

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

and this is my 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:

Well i didnt get any answer so this is what i have done

in HTML in ng-container

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

so i am calling a function passing the strings

and this is how i am retrieving formGroup

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