Angular 2 [(ngModel)] with *ngFor doesn't appear to work

11,381 views
Skip to first unread message

Anjum Naseer

unread,
Aug 11, 2016, 11:24:00 AM8/11/16
to AngularJS
Hi,

I cannot seem to get ngModel working correctly when it appears inside an ngFor. I have created a simple app that demonstrates the issue here: Plunker Demo

The HTML template in the demo (defined in src/app.ts) is:
<div>
  <form name="myForm">
    <div *ngFor="let item of items">
      <label>{{item.name}}:&nbsp;</label><input name="name" type="text" [(ngModel)]="item.name"/>
      <label>{{item.value}}:&nbsp;</label><input name="value" type="text" [(ngModel)]="item.value"/>
    </div>
  </form>
</div>

This is looping over an items array that is defined in the same file as:
export class App {
  constructor
() {
   
this.items = [
     
{name: 'Item 1', value: '123'},
     
{name: 'Item 2', value: '456'}
   
];
 
}
}

I expected to see a form containing these two rows:

Item 1: [Item 1] 123: [123]
Item 2: [Item 2] 456: [456]

but what I actually get is:

Item 1: [Item 2] 123: [456]
Item 2: [Item 2] 456: [456]

It seems like ngModel is not able to track the correct properties.

Am I doing something wrong here?

Anjum Naseer

unread,
Aug 11, 2016, 5:35:16 PM8/11/16
to AngularJS
I did a bit more investigation and seems like I made a mistake in the HTML template. I need to ensure that the input elements have unique names for each iteration of the *ngFor.

So the working version is as follows:
<div>
 
<form name="myForm">
   
<div *ngFor="let item of items; let index=index">
     
<label>{{item.name}}:&nbsp;</label><input name="{{'name'+index}}" type="text" [(ngModel)]="item.name"/>
     
<label>{{item.value}}:&nbsp;</label><input name="{{'value'+index}}" type="text" [(ngModel)]="item.value"/>
   
</div>
 
</form>
</div>

Jakub Beránek

unread,
Aug 11, 2016, 6:17:58 PM8/11/16
to AngularJS
Good catch :-)

You can simplify the input name binding slightly by using the property syntax
<input [name]="'name' + index" />

Anjum Naseer

unread,
Aug 11, 2016, 6:20:30 PM8/11/16
to AngularJS
Perfect! Many thanks Jakub :)

Sander Elias

unread,
Aug 11, 2016, 11:34:59 PM8/11/16
to AngularJS
Hi Ajum

Or leave the name attribute off completely.

Regards
Sander

Anjum Naseer

unread,
Aug 12, 2016, 7:45:11 AM8/12/16
to AngularJS
Hi Sanders,

Thank you for your suggestion. I tried it but get the following error:
Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.


     
Example 1: <input [(ngModel)]="person.firstName" name="first">
     
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

I am not sure of the implications of adding the ngModelOptions attribute. Would you know or is it better if I just stick to specifying unique names?

Regards,

Anjum.
Reply all
Reply to author
Forward
0 new messages