Rahul Dagli
Rahul Dagli

Reputation: 4502

How to dynamically define formControl name within ngFor loop?

I would like to dynamically populate fields based on the items containing within an object. I'm using reactive forms with angular material.

However, I'm getting:

Error: Cannot find control with unspecified name attribute

<div *ngFor="let field of guidelines.fields; let i=index">
  <mat-form-field>
    <input [formControl]="i" ngDefaultControl matInput placeholder={{field.field_name}} value={{field.notes}}>
  </mat-form-field>
</div>

Upvotes: 6

Views: 22000

Answers (2)

Rahul Dagli
Rahul Dagli

Reputation: 4502

Using form group:

HTML

<div [formGroup]="form" class="edit-guidelines">
  <div mat-dialog-content>
    <h2>Edit Guidelines</h2>
    <h3>{{guidelines.tab_name}}</h3>
    <div *ngFor="let field of guidelines.fields; let i=index">
      <mat-form-field>
        <input [formControlName]="field.field_name" ngDefaultControl matInput placeholder={{field.field_name}} value={{field.notes}}>
      </mat-form-field>
    </div>
  </div>
  <div mat-dialog-actions>
    <span class="right-align-next-element"></span>
    <button class="secondary-btn" mat-button (click)="closeModal()">Cancel</button>
    <button class="primary-btn" mat-button (click)="updateGuideline()" cdkFocusInitial>Update Manufacturer</button>
  </div>
</div>

TS

getGuideline() {
    this.guidelines = this.data.tabObj[0];
    console.log(this.guidelines);
    this.form = this.createGroup();
  }

  createGroup() {
    const group = this.fb.group({});
    this.guidelines.fields.forEach(control => group.addControl(control.field_name, this.fb.control('')));
    return group;
  }

Upvotes: 8

J. Pichardo
J. Pichardo

Reputation: 3115

The [formControl] directive take a FormControl as value and you are passing it a number, hence the Cannot find control with unspecified name attribute. I would have either a wrapping array or a separate array in order to access the formControls by index:

const wrappingArray = guidelines.fields.map(field => ({formControl, ...field}));

And use it

<div *ngFor="let field of wrappingArray; let i=index">
  <mat-form-field>
    <input [formControl]="field.formControl" ngDefaultControl matInput placeholder={{field.field_name}} value={{field.notes}}>
  </mat-form-field>
</div>

Or with a separate array

const formControls = [formControl1, ... formControlN];

And use it

<div *ngFor="let field of guidelines.fields; let i=index">
  <mat-form-field>
    <input [formControl]="formControls[i]" ngDefaultControl matInput placeholder={{field.field_name}} value={{field.notes}}>
  </mat-form-field>
</div>

Upvotes: 0

Related Questions