Is it not possible (or not yet possible) to use ngModel
against values from ngFor
? Is Angular trying to protect me from bad performance?
W
I think ngFor
don't like tracking array elements which are primitive values having ngModel
on them.
If you remove the ngModel
inside the loop, it works.
It works too when I update jsfiddle with :
this.names = [{name: 'John'}, {name: 'Joe'}, {name: 'Jeff'}, {name: 'Jorge'}];
and
<li *ng-for="#n of names"><input type="text" [(ng-model)]="n.name">{{n.name}}</li>
A solution is to reference the value inside ngModel
by its index. Therefore [(ngModel)]="names[index]"
.
But this is not sufficient because *ngFor
tracks items by value. As soon as the value is changed the old value cannot be tracked. So we need to change the tracking function to return an index, thus trackBy: trackByIndex
.
This issue is explained here.
Solution:
@Component({
selector: 'my-app',
template: `
<div>
<input type="text"
*ngFor="let name of names; let nameIndex = index; trackBy: trackByIndex"
[(ngModel)]="names[nameIndex]"/>
<br/>
{{ names | json }}
</div>
`,
})
export class App {
names: string[];
constructor() {
this.names = ['a', 'b', 'c'];
}
public trackByIndex(index: number, item) {
return index;
}
}