Angular2 ngFor OnPush Change Detection with Array Mutations

前端 未结 4 1901
深忆病人
深忆病人 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:24

    I too faced the similar issue where to optimize my app performance, I had to use the changeDetection.OnPush strategy. So I injected it in both my parent component as well as my child component's constructor , the instance of changeDetectorRef

        export class Parentcomponent{
           prop1;
    
           constructor(private _cd : ChangeDetectorRef){
              }
           makeXHRCall(){
            prop1 = ....something new value with new reference;
            this._cd.markForCheck(); // To force angular to trigger its change detection now
           }
        }
    

    Similarly in child component, injected the instance of changeDetectorRef

        export class ChildComponent{
         @Input myData: myData[];
         constructor(private _cd : ChangeDetectorRef){
              }
           changeInputVal(){
            this.myData = ....something new value with new reference;
            this._cd.markForCheck(); // To force angular to trigger its change detection now
           }
        }
    

    Angular change Detection is triggered on every asynchronous function :-

    • any DOM event like click,submit, mouseover.
    • any XHR call
    • any Timers like setTimeout(), etc.

    So, this kind of slows down the app because even when we are dragging the mouse, angular was triggering changeDetection. For a complex app spanning over multiple components, this could be a major performance bottleneck since angular has this tree kind of parent to child change detection strategy. To avoid, this it is better we use the OnPush strategy and forcefully trigger angular's change detection where we see there is a reference change.

    Secondly, in OnPush strategy, one should be very careful that it will only trigger change when there is a change in object reference and not just the object property value i.e in Angular change” means “new reference”.

    For eg:-

        obj = { a:'value1', b:'value2'}'
        obj.a = value3;
    

    The property value of 'a' in 'obj' might have change but obj still points to the same reference, so Angular change detection will not trigger here (unless you force it to); To create a new reference , need to clone the object into another object and assign its properties accordingly.

    for further understanding, read about Immmutable Data structures, change Detection here

提交回复
热议问题