首页 文章

Angular 2 ngModel绑定在嵌套的ngFor中

提问于
浏览
14

我正在尝试将Angular 1应用程序转换为Angular 2.循环通过锯齿状的布尔数组合 (boolean[][]) . 我使用以下代码渲染 checkboxes

<div *ngFor="#cell of CellData; #parentIndex = index">
    <input *ngFor="#col of cell; #childIndex = index" type="checkbox" [(ngModel)]="CellData[parentIndex][childIndex]" />      
</div>

复选框显示正确,但是,如果我选中一个复选框,也会选中右侧的复选框 .

这个逻辑在Angular 1应用程序中工作正常,所以我不确定这是否与我使用ngModel的方式或Angular 2的问题有关 .

任何帮助将非常感激

1 回答

  • 17

    Update

    使用 ngForTrackBy 的官方方式似乎是

    <input 
              *ngFor="let col of cell; let childIndex=index; trackBy:customTrackBy" 
              type="checkbox" 
              [(ngModel)]="CellData[parentIndex][childIndex]" />
    

    有关详细信息,请参阅http://angularjs.blogspot.co.at/2016/04/5-rookie-mistakes-to-avoid-with-angular.html

    请注意 trackBy:customTrackBy 中的 :

    original

    您可以使用 *ngForTrackBy

    @Component({
      selector: 'my-app', 
      template: `
        <div *ngFor="let cell of CellData; let parentIndex = index">
          <input 
              *ngFor="let col of cell; let childIndex = index" type="checkbox" 
              *ngForTrackBy="customTrackBy" 
              [(ngModel)]="CellData[parentIndex][childIndex]" />      
        </div>
    
        Data:

    {{CellData | json}} ` }) export class AppComponent { constructor() { this.CellData = [ [ true, false, true, false ], [ false, true, false, true ] ] } customTrackBy(index: number, obj: any): any { return index; } }

    Angular默认跟踪对象标识但不同的 truefalse 具有相同的标识 . 没有 *ngForTrackBy Angular looses轨道 truefalse 在哪个位置 . 使用 *ngForTrackBy="customTrackBy" ,我们使 *ngFor 使用索引而不是对象标识 .

    Plunker example

    也可以看看

相关问题