Tuesday, October 15, 2019

Understanding Change Detection Strategy onpush in Angular


Change Detection Strategy onpush in Angular

  1. https://alligator.io/angular/change-detection-strategy/
  2. https://stackblitz.com/edit/change-detection-strategy1
  3. https://blog.ninja-squad.com/2018/09/27/angular-performances-part-4/
  4. https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4 (VVI, ************, please study more)

Change Detection Strategy onpush follow some rules: You may need to take care this rules



Rule 1: @Inputs: Input properties value will be changed when its ref will be changed

Rule 2: A component have own internal state.  in the ts file , if value change due to api or set-timeout it will not show in html page directly. it only show when any event(click, change) occur from the html page.

Rule 3: We run change detection explicitly.  The first is detectChanges() which tells Angular to run change detection on the component and his children.

onstructor(private cdr: ChangeDetectorRef) {   
    setTimeout(() => {     
           this.count = 5;      this.cdr.detectChanges(); 
  }, 1000);
}

Rule 4: Angular Async Pipe. The async pipe subscribes to an observable or promise and returns the latest value it has emitted

see the example of above link

If a component depends only on its input properties, and they are observable, then this component can change if and only if one of its input properties emits an event.



Rule 5: onPush and View Queries.

 @Input() set content(value) {
    this._content = value;
    this.cdr.markForCheck();
  }



Rule 6:  === onPush++ (VVVVIIIIII)

Also, by creating a dedicated component we make our code more readable and reusable.


See the example of above medium doc link 


https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4










No comments:

Post a Comment

Autoboxing and Unboxing

  Autoboxing  is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper cl...