Angular 4 Dynamic form with nested groups

Taras Hupalo picture Taras Hupalo · Aug 13, 2017 · Viewed 9.2k times · Source

I want to generate a reactive form from the tree structure.

Here is the code that creates the form items (form groups and controls). For the controls nested in form group it I use a recursive template.

The form HTML is generated perfectly. But when I add the formControlName directive to the input the HTML generation breaks. Then I get such error:

Error: Cannot find control with name: 'answer1'

Answer

yurzui picture yurzui · Aug 13, 2017

To support unlimited number of nested group i would use markup like:

<ng-container [formGroup]="form">
  <ng-container 
     *ngTemplateOutlet="formItemTemplate; context:{ $implicit: 0, group: form }">
  </ng-container>

  <ng-template #formItemTemplate let-i let-group="group">
      <fieldset *ngIf="i < pathSegments.length - 1" class="form-group">
        <legend>{{ pathSegments[i] }}</legend>
        <ng-container 
          *ngTemplateOutlet="formItemTemplate; 
          context:{ $implicit: i + 1, group: group.get(pathSegments[i]) }">
        </ng-container>
      </fieldset>

      <div *ngIf="i + 1 === pathSegments.length" class="form-control" [formGroup]="group">
        <label>{{pathSegments[pathSegments.length - 1]}}</label>
        <input [formControlName]="pathSegments[pathSegments.length - 1]"/>
      </div>
  </ng-template>
</ng-container>

Plunker Example