Angular2可编辑表更新相邻单元格

时间:2017-02-20 12:43:07

标签: angular inline-editing

我对可编辑的表格有一种奇怪的行为。向表中添加行后,我将更改新行第一列中的值。更新后的值不仅显示在第一列中,还显示在新行的第二列中。在数据中,值是正确的,但这与屏幕上呈现的值不同。

Screendump of strange behaviour

我已尝试使用[(ngModel)](change)="updateCell(i,j, box.value, $event)"(blur)来更新表格中的单元格值,并获得相同的结果 - 数据是正确,但不是渲染的视图。

鉴于背景,这段代码有什么问题:

import { Component } from '@angular/core';

/**
 * This class represents the table component.
 */
@Component({
  moduleId: module.id,
  selector: 'table-component',
  template: `
    <H3>Editable table</H3>
    <table>
      <tr class="row" *ngFor="let row of data; let i=index;">
        <td class="col" *ngFor="let col of row; let j=index;">
          <div><input type="text" #box value="{{col}}"   
              (change)="updateCell(i,j, box.value, $event)" /></div>
        </td>
      </tr>
    </table>
    <button (click)="addRow()">Add row</button>&nbsp;
    <button (click)="addCol()">Add col</button>&nbsp;
    <H3>Resulting data table</H3>
    <table>
      <tr class="row" *ngFor="let row of data; let i=index;">
        <td class="col" *ngFor="let col of row; let j=index;">
          <div>{{col}}</div>
        </td>
      </tr>
    </table>
  `,
  styleUrls: ['table.component.css']
})    
export class TableComponent {
  noOfCols:number = 3;
  noOfRows:number = 4;
  data: any[] = [];

  constructor(){
    this.initializeData();
  }

  initializeData() {
    for (let row = 0; row < this.noOfRows; row++) {
      this.data.push([]);
      for (let col  = 0; col < this.noOfCols; col++) {
        this.data[row].push(row*this.noOfCols + col);
      }
    }
  }

  addRow() {
    let newRow: any[] = [];
    for (let column = 0; column < this.data[0].length; column++) {
      newRow.push('');
    }
    this.data.push(newRow);
  }

  addCol() {
    for (let row = 0; row < this.data.length; row++) {
      this.data[row].push('');
    }
  }

  updateCell(row:number, col:number, value:any, e:any) {
    e.stopImmediatePropagation();
    this.data[row][col] = value;
  }
}

稍后更改值时,第二列不会相应更新...

0 个答案:

没有答案