gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:16:27 24 4
gpt4 key购买 nike

我想根据对象中包含的项目动态填充字段。我正在使用带有 Angular Material 的 react 形式。

但是,我得到:

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

关于angular - 如何在 ngFor 循环中动态定义 formControl 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com