这是我的 HTML:
<tr *ngFor="let row of formData; let i = index" [attr.data-index]="i">
<td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j">
<input type="checkbox" name="row-{{i}}-{{j}}" [(ngModel)]="formData[i][j]">
</td>
</tr>
如您所见,我在复选框
上设置了唯一名称以将它们完全隔离。
formData
遵循如下结构:
formData = [
[false, false],
[true, true],
[false, true]
]
表单正确填充。
复选框生成正确,但是,有一些奇怪的行为:
当我点击第一列的复选框时,它也会选中第二列的复选框;这看起来完全是随机行为,但是当我选中第二列的复选框时,它对第一列的复选框没有影响
知道为什么会这样吗?
编辑
观察:我将输入
更改为标准输入(不是复选框)。
我将表单值更改为“true”、“false”……而不是 true、false。
当我尝试更改输入中的文本时,我只能输入一个字符并且输入框会“取消选择”(即,每次我输入一个字符时,我都必须一直点击输入框以激活它)
编辑
请求的 HTML 输出:
最佳答案
在第二个 ngFor 中使用 trackBy 使它对我有用:
模板:
<tr *ngFor="let row of formData['rows']; let i = index;" [attr.data-index]="i">
<td *ngFor="let rowdata of formData['rows'][i]; let j = index; trackBy: trackByIndex" [attr.data-index]="j">
<input type="checkbox" id="row-{{i}}-{{j}}" name="row-{{i}}-{{j}}" [(ngModel)]="formData['rows'][i][j]"/>
</td>
</tr>
组件:
定义 trackByIndex 函数:
trackByIndex(index: number, value: number) {
return index;
}
解释了使用 trackBy 的原因 here (致谢 zoechi@github):
you're iterating the items you're editing and they are primitive values. ngFor can't keep track by identity because when the value changes from 1 to 3 (by editing) it becomes a different identity. Either use a custom trackBy that tracks by index or use objects instead of primitive values.
关于javascript - 更新输入会影响其他输入但没有绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051898/