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
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: `
{{ names | json }}
`,
})
export class App {
names: string[];
constructor() {
this.names = ['a', 'b', 'c'];
}
public trackByIndex(index: number, item) {
return index;
}
}