Suman
Suman

Reputation: 97

Dynamic form is not working while using ng-container and ng-template

I am creating a dynamic form where I am getting the form fields form api. I am using ng-container & ng-template to reuse the formgroup multiple times but it's not working as expected. When I am using usual div it's working as expected.

https://stackblitz.com/edit/angular-ivy-hqc49t

Upvotes: 2

Views: 1076

Answers (1)

Yan Koshelev
Yan Koshelev

Reputation: 1129

You can use FormGroup instances instead of formGroupName, because template loses context of formGroup: Stackblitz

<ng-container
    *ngTemplateOutlet="
      fieldsTemplate;
      context: {
        formGroup: formGroundUse.get('groundUses')
      }
    "
  >
  </ng-container>
<div formArrayName="groundUsesArray">
groundUsesArray
<ng-container *ngFor="let data of groudUse.controls">
  <ng-container
    *ngTemplateOutlet="
      fieldsTemplate;
      context: {
        formGroup: data
      }
    "
  >
  </ng-container>
</ng-container>
<ng-template #fieldsTemplate let-formGroup="formGroup">
  <div [formGroup]="formGroup">
    <tr>
      <td class="input-container">
        <label for="">title</label>
        <input type="text" class="form-input" formControlName="title" />
      </td>
      <td class="input-container">
        <label for="">value</label>
        <input type="text" class="form-input" formControlName="value" />
      </td>
      <td class="input-container">
        <label for="">percentage</label>
        <input type="number" class="form-input" formControlName="percentage" />
      </td>
    </tr></div
></ng-template>

Upvotes: 4

Related Questions