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

Time:06-16

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

CodePudding user response:

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 >
        <label for="">title</label>
        <input type="text"  formControlName="title" />
      </td>
      <td >
        <label for="">value</label>
        <input type="text"  formControlName="value" />
      </td>
      <td >
        <label for="">percentage</label>
        <input type="number"  formControlName="percentage" />
      </td>
    </tr></div
></ng-template>
  • Related