Angular2 ng For OnPush变化检测与阵列突变

amc*_*dnl 14 angular2-changedetection angular

我有一个数据表组件(angular2-data-table)项目,我们将项目从Angular的传统变化检测更改OnPush为优化的渲染速度.

一旦实施了新的变更检测策略,就会在数据对象发生变异时引用该表而未更新的错误,例如对象的属性更新参考:https://github.com/swimlane/angular2-data-table/issues/ 255.对于诸如股票代码之类的大型数据集合中的单个属性的内联编辑或外部数据更改之类的事情,可以使用强大的用例.

为了解决这个问题,我们添加了一个名为的自定义trackBy属性检查器trackByProp.参考:提交.不幸的是,这个解决方案没有解决问题.

在实时重新加载的演示页面上,您可以看到上面提交运行中引用的演示但不更新表,直到您单击从而触发更改检测.

组件的结构类似于:

Table > Body > Row Group > Row > Cell

所有这些组件都实现了OnPush.我使用的getter/setter方法在行二传手触发网页重新计算像显示在这里.

我们希望继续OnPush对实现此模式的人进行更改检测,但是,作为一个具有多个消费者的开源项目,可以为屏幕上的可见行值争论某种自定义检查功能.

所有这一切,trackBy都没有触发行单元格值的变化检测,实现这一目标的最佳方法是什么?

Gün*_*uer 24

Angular2变化检测不检查数组或对象的内容.

一个hacky解决方法是在变异后创建一个数组副本

this.myArray.push(newItem);
this.myArray = this.myArray.slice();
Run Code Online (Sandbox Code Playgroud)

这种方式this.myArray引用不同的数组实例,Angular将识别更改.

另一种方法是使用IterableDiffer(对于数组)或KeyValueDiffer(对象)

// inject a differ implementation 
constructor(differs: KeyValueDiffers) {
  // store the initial value to compare with
  this.differ = differs.find({}).create(null);
}

@Input() data: any;

ngDoCheck() {
  var changes = this.differ.diff(this.data); // check for changes
  if (changes && this.initialized) {
    // do something if changes were found
  }
}
Run Code Online (Sandbox Code Playgroud)

另见https://github.com/angular/angular/blob/14ee75924b6ae770115f7f260d720efa8bfb576a/modules/%40angular/common/src/directives/ng_class.ts#L122