Pankaj Parkar
Indian | 30 | Ex MVP | Angular GDE
Data / Model / State
Template
DOM
{
"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
Technical Lead
Synerzip Softech India PVT LTD
@pankajparkar
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
@pankajparkar
//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()
@pankajparkar
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()
@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
@pankajparkar
Change detection fires
CD -> Change Detection
@pankajparkar
@Input() name1
@Input() name2
[name]="name2"
[name]="name1"
name1 = 'Ravi'
name2 = 'Pankaj'
name1 = 'Ravi'
name2 = 'Keerti'
OnPush
OnPush
@pankajparkar
Source: https://blog.angularindepth.com/a-gentle-introduction-into-change-detection-in-angular-33f9ffff6f10
@pankajparkar
(further exploration)
@pankajparkar
@pankajparkar
By Pankaj Parkar
Demystifying Change Detection in Angular