angular - 使用 [(ngModel)] 与 ngFor 的 2 路数据绑定,数组不会更新行的值
问题描述
这是html代码:
<table class="table table-hover table-bordered table-striped table-highlight">
<thead>
<tr>
<th *ngFor="let cell of tableData2.headerRow">{{ cell }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of tableData2.dataRows">
<td *ngFor="let cell of row">
<input type="text" class="form-control border-input" [(ngModel)]="cell" name="cell" />
</td>
</tr>
</tbody>
</table>
这是相关的打字稿代码:
declare interface TableData {
headerRow: string[];
dataRows: string[][];
}
public tableData2: TableData;
this.tableData2 = {
headerRow: ['Version', 'Approbateur(nom+fonction)', 'Principales remarques', 'Date d\'approbation'],
dataRows: [
['ahmed', '', '', ''],
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
]
};
您可能已经注意到,双向数据绑定在“一个方向”上工作,值“ahmed”确实会显示出来。
但是,当我像这样更改表中输入的值时:
然后我控制台记录 tableData2 变量:
您可能会注意到,新值 SAM 不会在 tabledata 变量中更新。即,双向数据绑定不起作用,我无法从表中检索值。
我做错了什么?
解决方案
2路绑定对数组值不起作用,它需要一些对象来更新
所以第一个变化是let i = index;
and [(ngModel)]="row[i]"
:
<td *ngFor="let cell of row;
let i = index;
trackBy: customTrackBy
">
<input type="text" class="form-control border-input" [(ngModel)]="row[i]" name="cell" />
</td>
第二个变化:(问题在演示中显示)
// Your list will be reloaded again by ngFor when you change one field value,
// and it will lose the focus.
// You can add a trackBy to determine if the list must or must not be reloaded. The code below seems to solve the issue:
customTrackBy(index: number, obj: any): any {
return index;
}
工作演示(带有解决方案+问题)
推荐阅读
- javascript - 如何显示树的选定节点 - JSTree jQuery
- python - 默认创建后 Jupyter Book 构建失败
- python - conda 包无法安装到 PyCharm 虚拟环境中?
- python - 使用 Python 的 Choropleth 地图
- spring - RestController Advice 上的自定义 HTTP 状态代码(在 900 系列中)
- python - 自定义 Ansible 模块 Python XlSXWRITER 无法格式化大于 Z 的行
- java - android意图片段到活动有错误
- javascript - 如何在注册用户之前检查用户凭据,同时将图像上传到 aws s3
- deep-learning - 内核大小均匀时相同的填充
- python - 在 Python Tkinter 中,如何使用名称获取嵌入在文本小部件中的图像的索引?