DEV Community

Deepa Chaurasia
Deepa Chaurasia

Posted on

What is Change Detection in Angular?

Change detection is *detecting changes in any component * of your app and re-render view, so it displays updated value to end users.

Different events on which change occurs:

  • Data received from network requests or component events.
  • Mouse clicks,scrolling,mouseover,keyboard navigation

  • AJAX Calls

  • Use of timer function such as setTimeout() or setInterval().

How does Change detection work??

  • Whenever something triggers a change.

  • To detect and update DOM with changed data,the framework provides its own change detection detector for each component.

  • The change detector make sure data model and DOM are in sync.

  • When Angular change detection detects the triggered change and run change detection to all component tree from top to bottom.

Angular Change Detection strategies

There are two strategies basically in angular:-

  • Default Change Detection Strategy

  • OnPush Change Detection Strategy

Default Change Detection Strategy

If Angular Change Detector is set to default then for any change in any model property, Angular will run change detection traversing component tree to update DOM.

Change Detector Ref class provides few built in methods , we can use to manipulate change detection tree.

  • markForCheck() - marks that it changed.

  • detach() - exclude view from change detection tree

  • detect Changes() - check view and its child component

  • checkNoChanges() -check view and it's child ,throw error if changes detected.

  • reattach() - reattach a view that was previously detached

Angular OnPush Change Detection Strategy

If angular change detector is set to onPush then Angular will run change detector only when new reference is being passed to component.

If observable is passed to onPush, then changeDetector must be called manually to update DOM

Benefits

Unnecessary check in child not performed if parent element updating values which are not passed @Input

Image description

Here we have changed strategy to OnPush

Hope it help you guys :)

Please like share and subscribe if you like it

Top comments (1)

Collapse
 
hendrikras profile image
Hendrik Ras

Good point, but a bit short perhaps? Perhaps you could go in depth with some examples?