Angular2-NgFor内部树模型:删除然后添加元素时顺序错误

Angular2 NgFor inside tree model: wrong order when remove and then add elements

本文关键字:元素 添加 顺序 错误 然后 删除 内部 模型 Angular2-NgFor      更新时间:2023-09-26

我在玩角2阿尔法44。

我有一个树模型,并使用递归性来显示它。每个组包含"标准"、"分段"和其他"组"。我们可以在任何级别删除和添加所有这些元素。

当我删除元素,然后在同一级别上添加其他元素时,会出现一种奇怪的行为。新的顺序是错误的,新元素具有更大的position属性,数组根据该属性进行排序,但它们出现在删除元素的位置。。

新阵列将记录在控制台中,并按正确的顺序显示。如果使用"SHOW/HIDE"按钮删除和添加所有树,则视图现在的顺序是正确的。

你可以在这个plunker中看到这种行为,并且很容易理解:

  1. 移除第一个元素
  2. 添加新元素
  3. 请查看视图中的顺序不正确,并且与控制台日志
  4. 在"显示/隐藏"按钮上单击2次
  5. 查看视图中的顺序是否正确

有类似ng1 trackBy和ng2 NgFor的东西吗?我在内部消息来源中什么也没发现。。

trackBy是在2.0.0测试版3 中添加的

另请参阅https://github.com/angular/angular/issues/4402

带有模板元素:

@Component(
  template: `
   <template ngFor let-item [ngForOf]="items" [ngForTrackBy]=customTrackBy">
      {{item}}
   </template>
   `
)
class MyComponent {
  customTrackBy(index: number, obj: any): any {
    return index;
  }
}

带*ngFor:

@Component(
  template: `
   <div *ngFor="let item of items; trackBy:customTrackBy">
      {{item}}
   </div>
   `
)
class MyComponent {
  customTrackBy(index: number, obj: any): any {
    return index;
  }
}

另请参阅https://github.com/angular/angular/issues/6872

我可以使用**ngFor="let character of characters | async" *ngForTrackBy="customTrackBy"

或者我可以使用*ngFor="let character of characters | async ; trackBy:customTrackBy"

另请参阅嵌套ngFor 中的Angular 2 ngModel绑定