Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngModel inside ngFor (Data not binding on input)

Tags:

angular

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>
like image 728
Ashwath S H Avatar asked Sep 05 '16 19:09

Ashwath S H


People also ask

Is ngModel property binding?

NgModel is a directive that creates the FormControl instance from a domain model and binds it to a form control element. It uses two kinds of binding: Property binding.

Can I use ngModel without form?

standalone: When set to true, the ngModel will not register itself with its parent form, and acts as if it's not in the form.


1 Answers

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>
like image 146
Yaroslav Stavnichiy Avatar answered Oct 19 '22 11:10

Yaroslav Stavnichiy