【问题标题】:Angular 2 ngModel bind in nested ngForAngular 2 ngModel 在嵌套的 ngFor 中绑定
【发布时间】:2016-07-27 22:52:09
【问题描述】:

我正在尝试将 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 有问题。

任何帮助将不胜感激

【问题讨论】:

  • 你能提供一个 Plunker 来演示这个问题吗?
  • 看到这个 plunkr plnkr.co/edit/BbZxbAS0jNafAfI6slq9?p=preview, @Gunter。真的很奇怪关联对应于更新但视图是不同步的......
  • 先搞定,我正要为它贴一个plunker ;)
  • 谢谢@ScottLyons,我遇到了在 ngFor 中使用 ngModel 的问题,没有办法做到这一点,你的问题对我有帮助。 :)

标签: angular


【解决方案1】:

更新

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 默认跟踪对象身份,但不同的 trues 和 falses 具有相同的身份。没有*ngForTrackBy Angular 会丢失truefalse 位于哪个位置的轨道。对于*ngForTrackBy="customTrackBy",我们让*ngFor 使用索引而不是对象标识。

Plunker example

另见

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 2019-05-06
    • 2017-03-11
    • 2018-06-11
    • 2018-10-13
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多