如何在 ngFor 循环中动态定义 formControl 名称? [英] How to dynamically define formControl name within ngFor loop?
本文介绍了如何在 ngFor 循环中动态定义 formControl 名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据对象中包含的项目动态填充字段.我正在使用带有角材料的反应形式.
但是,我得到:
<块引用>错误:找不到具有未指定名称属性的控件
<mat-form-field><input [formControl]="i" ngDefaultControl matInput placeholder={{field.field_name}} value={{field.notes}}></mat-form-field>
解决方案
使用表单组:
HTML
<div mat-dialog-content><h2>编辑指南</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 mat-dialog-actions><span class="right-align-next-element"></span><button class="secondary-btn" mat-button (click)="closeModal()">取消</button><button class="primary-btn" mat-button (click)="updateGuideline()" cdkFocusInitial>更新制造商</button>
TS
getGuideline() {this.guidelines = this.data.tabObj[0];console.log(this.guidelines);this.form = this.createGroup();}创建组() {const group = this.fb.group({});this.guidelines.fields.forEach(control => group.addControl(control.field_name, this.fb.control('')));返回组;}
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>
解决方案
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;
}
这篇关于如何在 ngFor 循环中动态定义 formControl 名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!