我正在尝试将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>
Run Code Online (Sandbox Code Playgroud)
复选框显示正确,但是,如果我选中一个复选框,也会选中右侧的复选框.
这个逻辑在Angular 1应用程序中工作正常,所以我不确定这是否与我使用ngModel的方式或Angular 2的问题有关.
任何帮助将非常感激
Gün*_*uer 17
更新
官方的使用方式ngForTrackBy
似乎是
<input
*ngFor="let col of cell; let childIndex=index; trackBy:customTrackBy"
type="checkbox"
[(ngModel)]="CellData[parentIndex][childIndex]" />
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参见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;
}
}
Run Code Online (Sandbox Code Playgroud)
Angular默认跟踪对象标识,但不同的true
s和false
s具有相同的标识.没有*ngForTrackBy
角度松动跟踪哪个true
或false
哪个位置.随着*ngForTrackBy="customTrackBy"
我们作出*ngFor
使用索引,而不是对象标识.
也可以看看