Nested ngFor with two-way data binding Angular2


I try to make a table of input fields with help of nested ngFor with two-way data binding. I almost achieved this, but something with two-way data binding is wrong and I can’t find a problem.

So, this is what I want to have – I want to be able type each letter of word in.

My examle table with inputs fieleds

I have this table, and I am able to type in, but if I type in first cell, the same value appears in second, if I type in third, value appears also in 4th and 5th…
And I can’t understand why, I guess the problem is with this line

<input maxlength="1" size='5' name="{{i}}{{j}}" [(ngModel)]="helper[i][j]" [id]="j"/>

Could you please tell me, how could I fix this one?
Here is my plunker, it works, but with this mistake, that I described above…
My plunker is here


When using *ngFor, you should try to avoid accessing directly the arrays you are iterating on, like with [(ngModel)]="helper[i][j]".

Generally, you should try to always works with full object and dot(.) notation when using data binding.

In your case, just replace the raw array ['','','','',''] by an array of objects [value: '', value: '', value: '', value: '', value: ''] and bind it directly.

<td *ngFor="let item2 of helper[i]; let j = index;">
    <input maxlength="1" size='5' name="{{i}}{{j}}" [(ngModel)]="item2.value" [id]="j"/>

I have updated your plunker

Answered By – Noémi Salaün

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.