5

I had a working angular form with repeating templates inside two conditions, so i have moved it out to a common place and defined ngContainer to display the value by passing the variables, however inside the template, the code is not able to figure out the form and im getting the below error

BulkEditComponent.html:28 ERROR Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup
       directive and pass it an existing FormGroup instance (you can create one in your class).

Template

 <h5 mat-dialog-title>
   Edit
  </h5>
  <div mat-dialog-content class="body p-10">
    <div *ngFor="let item of keyList;let i=index" [formGroup]="editForm">

      <div class="left" *ngIf="i%2 == 0">
        <ng-container *ngTemplateOutlet="columnData;context:{item:item,group: editForm}"></ng-container>
      </div>

      <div class="right" *ngIf="i%2 == 1">
        <ng-container *ngTemplateOutlet="columnData;context:{item:item,group: editForm}"></ng-container>
      </div>

    </div>
  </div>
  <mat-dialog-actions class="align-right">
    <button mat-button mat-dialog-close>Cancel</button>
    <button mat-flat-button color="primary" (click)="formatData()">Update</button>
  </mat-dialog-actions>

  <ng-template #columnData let-item='item' ;let-formGroup="editForm">
    <div class="row p-2">
      <div class="col-md-6">
        {{getColumnName(item)}}
      </div>
      <div class="col-sm-6">
        <input type="text" class="input-field" [formControlName]="item" />
      </div>
    </div>
  </ng-template>
BLACKMAMBA
  • 675
  • 2
  • 11
  • 28
  • [Here is solution for your question](https://stackoverflow.com/questions/45742591/how-to-use-reactive-forms-inside-ng-template) – Sameer Jul 25 '19 at 10:12
  • in my case im not able to get the formgroup niside ng template, they are having the formgroup inside the template itself, while i need it to be shared from the top level – BLACKMAMBA Jul 25 '19 at 10:31
  • 7
    use `[formControl]="editForm.get(item)"` not [formControlName]="item" – Eliseo Jul 25 '19 at 12:07
  • for strictTemplates: ture, you need to cast abstract control type to ng control `[formControl]="$any(form.get(item.formControlName))" ` – kin Sep 06 '21 at 05:06

0 Answers0