首页 > 解决方案 > 使用 [(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 变量中更新。即,双向数据绑定不起作用,我无法从表中检索值。
我做错了什么?

标签: angularangular-ngmodelngmodelangular2-ngmodel

解决方案


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

工作演示带有解决方案+问题


推荐阅读