Angular 2 ngModel绑定在嵌套的ngFor中

时间:2016-04-07 07:42:16

标签: angular

我正在尝试将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 个答案:

答案 0 :(得分:17)

<强>更新

使用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

<强>原始

您可以使用*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:<br/><br/>
    {{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

另见