Angular2 ngFor OnPush Change Detection with Array Mutations

Angular2 change detection doesn’t check the contents of arrays or object.

A hacky workaround is to just create a copy of the array after mutation

this.myArray.push(newItem);
this.myArray = this.myArray.slice();

This way this.myArray refers a different array instance and Angular will recognize the change.

Another approach is to use an IterableDiffer (for arrays) or KeyValueDiffer (for objects)

// 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
  }
}

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

Leave a Comment