How to dynamically define formControl name within ngFor loop?

倖福魔咒の 提交于 2019-12-19 10:19:10

问题


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>

回答1:


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;
  }



回答2:


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>


来源:https://stackoverflow.com/questions/50374174/how-to-dynamically-define-formcontrol-name-within-ngfor-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!