I'm having a strange behaviour with an editable table. After adding a row to the table, I'm changing the value in the first column of the new row. The updated value is not only shown in the first column, but also in the second column of the new row. In the data, the values are correct but this differs from what is rendered on the screen.
Screendump of strange behaviour
I've tried to use [(ngModel)]
, (change)="updateCell(i,j, box.value, $event)"
and also (blur)
to update the cell values in the table and I'm getting the same result - data is correct, but not the rendered view.
Given that background, what is wrong in this code:
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>
<button (click)="addCol()">Add col</button>
<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;
}
}
When later changing the value, the second column is not updated accordingly...