如何在ngFor循环中动态定义formControl名称? [英] How to dynamically define formControl name within ngFor loop?
本文介绍了如何在ngFor循环中动态定义formControl名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据对象中包含的项目动态填充字段.我正在使用带有角形材料的反应形式.
I would like to dynamically populate fields based on the items containing within an object. I'm using reactive forms with angular material.
但是,我得到了:
错误:找不到具有未指定名称属性的控件
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>
推荐答案
使用表单组:
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;
}
这篇关于如何在ngFor循环中动态定义formControl名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文