Demystifying Change Detection in Angular

Data / Model / State

Template

DOM

Application Architecture

{
  "user": {
    "firstName": "Pankaj",
    "lastName": "Parkar",
    "age": 27
  }
}
<div class="card">
  First Name: {{user.firstName}}
  Last Name: {{user.lastName}}
  Age: {{user.age}}
</div>
First Name: Pankaj
Last Name: Parkar
Age: 27

28

28

@pankajparkar

Pankaj P. Parkar

Technical Lead

Synerzip Softech India PVT LTD

  • Microsoft MVP (3 times)

  • Opensource Contributor

  • Stackoverflow Topuser for Angular and AngularJS

  • 100k+ reps on Stackoverflow

  • Community Contributor

About Me!

@pankajparkar

What is Change Detection?

In simple word, it synchronises the model changes to view.

import { 
 Component
} from '@angular/core';

@Component({ ... })
export class AppComponent {
  title  = 'Angular'
}
<span>
  {{title}}
</span>
<button (click)="title='Changed'">
  Change Title
</button>

Change Title

Angular

Changed

Click

@pankajparkar

When should Change Detection happen?

  • As soon as an application state changes
  • What can cause state change?
    • Event Callback
    • Network (XHR) call
    • Timers (setTimeout, setInterval)

@pankajparkar

Possible Implementation

//network Call
getDataFromServer()
.then(()=> {
   //state has changed
   detectChanges();
})
//timeout function
setTimeout(()=> {
   //Call change detection
   detectChanges();
}, 5000)
element.addEventListner('click', (event) =>{
   //state could have change
   detectChanges();
});
let detectChanges => () => {
  if(currentState != prevState)
    updateView(currentState);
}

Detect Changes Method

@pankajparkar

function A () {
  ....
}

function B () {
  ....
  A();
}

function C () {
  ....
  B()
}

C(); // call C function

Call Stack

main()

C()

B()

A()

Javascript Execution

@pankajparkar

Javascript Execution Asynchronous

Callstack

Web API's

Queue

function A () {
  ...
}

function B () {
  ...
  A()
}

B()

setTimeout(() => {
   doSomething()
}, 2000)

B()

A()

setTimeout

doSomething()

@pankajparkar

  • ZoneJS to the rescue

  • Not a part of Angular Framework

  • monkey Patches macrotasks

let originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = (data) => {
  //monkey patch code
  if ( URL DOES NOT POINT TO AD SERVER ) {
    return originalSend.apply(this, arguments);
  }

  return false;
};

Zone.afterInvoke()

ZoneJS

@pankajparkar

import { 
 Component
} from '@angular/core';

@Component({ ... })
export class AppComponent {
  title  = 'Angular'
}
{
  context: new AppComponent(),
  viewDef: viewDefination,
  nodesDef: [],
  ViewChecked: true,
  .....
}

component

view

@pankajparkar

appliction_ref.ts

@pankajparkar

appliction_ref.ts

Source: https://github.com/angular/angular/blob/master/packages/core/src/application_ref.ts#L513-L532

@pankajparkar

Change Detection Strategy

  • Default
  • OnPush

@pankajparkar

Change detection fires

CD -> Change Detection

Change detection Default Strategy

@pankajparkar

@Input() name1

@Input() name2

[name]="name2"

[name]="name1"

name1 = 'Ravi'

name2 = 'Pankaj'

name1 = 'Ravi'

name2 = 'Keerti'

Change detection OnPush Strategy

OnPush

OnPush

@pankajparkar

Source: https://blog.angularindepth.com/a-gentle-introduction-into-change-detection-in-angular-33f9ffff6f10

@pankajparkar

ChangeDetectorRef

  • detectChanges
  • markForCheck
  • detach
  • reattach

(further exploration)

@pankajparkar

@pankajparkar

References

  • https://blog.angularindepth.com/a-gentle-introduction-into-change-detection-in-angular-33f9ffff6f10
  • https://blog.angularindepth.com/these-5-articles-will-make-you-an-angular-change-detection-expert-ed530d28930
  • https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f
  • https://blog.angularindepth.com/angulars-digest-is-reborn-in-the-newer-version-of-angular-718a961ebd3e?source=---------178---------------------
  • https://www.youtube.com/watch?v=CUxD91DWkGM
  • https://github.com/pankajparkar/demystifying-change-detection

Demystifying Change Detection in Angular

By Pankaj Parkar

Demystifying Change Detection in Angular

Demystifying Change Detection in Angular

  • 786