Angular2 ngModel against ngFor variables

后端 未结 2 1934
迷失自我
迷失自我 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

    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>
    
    0 讨论(0)
  • 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: `
        <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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题