如何解决如何在 ngFor 中使用 [(ngModel)] 和动态名称 (Key)
我有 NgFor 在两个不同的 div 上生成的角形式。我想让表单字段独一无二。 both fields are not working individually
<div *ngFor="let configField of configFields; let i = index"><mat-form-field fxFlex fxFlex.lt-md="calc(50% - 16px)" >
<input matInput placeholder="Url" name="url_{{i}}" [(ngModel)]="headerFields.url" >
</mat-form-field>
<mat-form-field fxFlex fxFlex.lt-md="calc(50% - 16px)" >
<input matInput placeholder="Method" name="type_{{i}}" [(ngModel)]="headerFields.type">
</mat-form-field></div>
我想在 (headerFields)Array 中唯一标识的字段名称上添加标志.. like name="type_{{i}}" type_1,type_2
解决方法
在 configFields 的初始化或分配时,您可以初始化或分配给 headerFields 一个长度等于 configFields 的数组,并将 url 和 type 设置为空。类似于以下内容:
const configFields = [1,2,3];
const headerFields = Array.from(configFields,(el) => ({ url: '',type: ''})) // Set to empty string or null as desired]
改用表单数组怎么样?
文件 component.ts
export class AppComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = fb.group({
config: fb.array([])
});
}
addNewAddressGroup() {
const add = this.form.get('config') as FormArray;
add.push(
this.fb.group({
url: [],type: []
})
);
}
deleteAddressGroup(index: number) {
const add = this.form.get('config') as FormArray;
add.removeAt(index);
}
}
文件 html.ts
<div [formGroup]="form">
<div>
<button (click)="addNewAddressGroup()">Add</button>
</div>
<div
*ngFor="let addressGroup of form.get('config').controls;let i = index"
[formGroup]="addressGroup">
<div>Url <input formControlName="url" /></div>
<div>Type <input formControlName="type" /></div>
<button (click)="deleteAddressGroup(i)">Delete</button>
</div>
</div>
result <br />
<pre>
{{form.value | json}}
</pre>
你可以看看这个Demo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。