我不明白为什么这段代码总是只打印数组的第一个元素重复两次("AAA","AAA")我错过了什么吗?也许我使用了错误的数据绑定。
TS:
var x ="AAAA,BBBB";
this.items = x.split(',');
.HTML:
<div *ngFor="let item of items;let i = index">
<input [(ngModel)]="model.arrayListVariables [i]" name="variable{{i}}" formControlName="variable" class="form-control" type="text">
</div>
https://stackblitz.com/edit/angular-hzlzea
谢谢
从您的堆栈闪电战代码中,我发现了以下问题。
您对两个输入使用相同的formControlName
,即 variable
.您需要为不同的输入使用不同的名称。
因此,我建议您进行如下更改:
app.component.html
...
<div *ngFor="let item of items;let i = index">
<input [(ngModel)]="item" name="variable{{i}}" [formControlName]="'variable'+i" type="text">
</div>
...
app.component.ts
...
this.form = this.formBuilder.group({
variable0: [''],
variable1: ['']
});
...
我还建议不要在形式上同时使用模板驱动和响应式方法。您可以在 Angular 表单简介中找到更多信息。