Angular2 ngFor OnPush Change Detection with Array Mutations

前端 未结 4 1921
深忆病人
深忆病人 2020-12-03 04:00

I have a data table component ( angular2-data-table ) project where we changed the project from Angular\'s traditional change detection to OnPush for optimized

4条回答
  •  心在旅途
    2020-12-03 04:03

    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

提交回复
热议问题