34

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>
Ashwath S H
  • 481
  • 1
  • 4
  • 13
  • 2
    Could you please remove id from your input tag, it will result in multiple elements in DOM with same id since you are running it inside a for loop. And why not use `item.lastname` and `item.middlename` instead of `item[in].lastname` – Savaratkar Sep 26 '16 at 11:27
  • I am sure you must have imported `FormsModule` in your respective component. – Savaratkar Sep 26 '16 at 11:29

2 Answers2

86

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>
Yaroslav Stavnichiy
  • 20,738
  • 6
  • 52
  • 55
0

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

Eduard Kolosovskyi
  • 1,396
  • 12
  • 18