使用 [(ngModel)] 2 路数据绑定与 ngFor ,数组不会更新行的值

Ahm*_*rib 1 angular-ngmodel angular2-ngmodel ngmodel angular

我已经建立了这个表格: 在此处输入图片说明

这是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>
Run Code Online (Sandbox Code Playgroud)

这是相关的打字稿代码:

declare interface TableData {
  headerRow: string[];
  dataRows: string[][];
}
public tableData2: TableData;
this.tableData2 = {
  headerRow: ['Version', 'Approbateur(nom+fonction)', 'Principales remarques', 'Date d\'approbation'],
  dataRows: [
    ['ahmed', '', '', ''],
    ['', '', '', ''],
    ['', '', '', ''],
    ['', '', '', ''],
    ['', '', '', ''],
    ['', '', '', ''],
    ['', '', '', ''],
  ]
};
Run Code Online (Sandbox Code Playgroud)

您可能已经注意到,双向数据绑定在“一个方向”起作用,值“ahmed”确实会显示。
但是,当我像这样更改表中输入的值时:
在此处输入图片说明 然后我 consoleLog tableData2 变量:
在此处输入图片说明 您可能会注意到,新值 SAM 不会在 tabledata 变量中更新。即,双向数据绑定不起作用,我无法从表中检索值。
我做错了什么?

Viv*_*shi 9

2 路绑定对数组值不起作用,它需要一些对象来更新

所以第一个变化let i = index;[(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>
Run Code Online (Sandbox Code Playgroud)

第二个变化:(问题显示在演示中)

// 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;
}
Run Code Online (Sandbox Code Playgroud)

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