如何在ngFor循环中动态定义formControl名称?

时间:2018-05-16 14:57:17

标签: angular angular-material

我想根据对象中包含的项动态填充字段。我正在使用带角度材料的反应形式。

但是,我得到了:

  

错误:找不到具有未指定名称属性的控件

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

2 个答案:

答案 0 :(得分:3)

使用表单组:

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

答案 1 :(得分:0)

[formControl]指令将FormControl作为值并且您传递一个数字,因此无法找到具有未指定名称属性的控件。我会有一个包装数组或一个单独的数组,以便通过索引访问formControls:

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

并使用它

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

或使用单独的数组

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

并使用它

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