Angular2 ngModel against ngFor variables

后端 未结 2 1935
迷失自我
迷失自我 2020-12-30 02:22

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

2条回答
  •  一整个雨季
    2020-12-30 02:56

    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; } }

提交回复
热议问题