Ashwath S H
Ashwath S H

Reputation: 581

Angular2 ngModel inside ngFor (Data not binding on input)

This is my Angular2 application with input fields inside table. My data is displaying on select tag but the data binded using ngModel on input tag is not been displayed in input field.

<form name="userForm">
<table>
<tr *ngFor="let item of itemList; let in =index">
  <td><select><option >{{item.FirstName}}</option></select></td>
  <td><input type="text" id="lastname" name="lastname" [(ngModel)]="itemList[in].lastname"></td>
  <td><input type="text" id="middlename" name="middlename" [(ngModel)]="itemList[in].middlename"></td>
</tr>
</table>
</form>

Upvotes: 34

Views: 33416

Answers (2)

Eduard Kolosovskyi
Eduard Kolosovskyi

Reputation: 1584

An alternative for Yaroslav's method: set [ngModelOptions]="{standalone: true}" to input

P.S. make sure you know what standalone option is https://angular.io/api/forms/NgModel#options

Upvotes: 0

Yaroslav Stavnichiy
Yaroslav Stavnichiy

Reputation: 21476

When creating multiple ngModel controls inside ngFor loop make sure to give each control unique name:

<form name="userForm">
<table>
<tr *ngFor="let item of itemList; let in = index">
  <td><input type="text" name="lastname-{{in}}" [(ngModel)]="item.lastname"></td>
  <td><input type="text" name="middlename-{{in}}" [(ngModel)]="item.middlename"></td>
</tr>
</table>
</form>

Upvotes: 86

Related Questions