David
David

Reputation: 175

Changing the value in a binded Angular table with [(NgModel)] affects other fields

I have a table with 1 character long fields that gets generated by *ngFor from a 2-dimensional array, defined as:

<table>​
    <tr *ngFor="let row of table; index as i">
        <td *ngFor="let field of row; index as j">
            <input type="text" [(ngModel)]="table[i][j]" type="text" maxlength="1" contenteditable="true" />
        </td>​
    </tr>​
</table>​

The idea is to let the user modify the contents of table in a visual manner and to get straight away the modified table to process its contents.

The problem comes when modifying the value in a single field, as it affects randomly to other fields in the same line. I have recreated the problem with random values in the following link:

StackBlitz Demo

Upvotes: 0

Views: 364

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

You can fix this by adding a "trackBy" function to your *ngFor loops. Updated StackBlitz demo at https://stackblitz.com/edit/angular-t7f9hx

Upvotes: 2

Related Questions