Angular 2.0 Change detectionRAN WAHLE
Agenda
A little about Angular 1.x The Angular 2.0 component change detector Angular and zone Immutables Observables Summary
A little bit about me
(Soon to be) Javascript developer @Tikal Consultant, speaker Volunteer in several programming projects Not a UI person
AngularJs 1.x scopes tree
Angular 1.x change detection
Angular 1.x summary
Prototypical inheritance of scopes Generic mechanism for change detection Change detection is not predictable
Angular 2.0 change detection goals
Performance Easy to use Transparency
Angular 2.0 change detection
Predictable Tree instead of graph
Angular 2.0 events
Zone.js Overrides web api for addEventListener, XHR, Timers, WebSockets
and more… Overriding will
Assign the callback Run change detection Update the UI
Change detection tree@component
@component@component
@component@component
@component
@component@component
@component
Change detector
Each component has its own change detector, created in compilation time
It may be found under <ComponentClassName>.ngfactory It has a detectChangeInternal method tailored to its data Its detectChangeInternal calls detectContentChildrenChanges
and detectViewChildrenChanges
Change detector Demo
How a change is determined
Javascript objects are mutable The default change detector, detect a reference change
myObj = new {prop: ‘value’}
myObj.prop =‘otherValue’;
OnPush strategy
There are two change detection strategies Default will trigger change detection whenever a bounded object is
changed OnPush will trigger change detection whenever an @Input decorated
object is changed.
ImmutableJs
Javascript objects are mutable Whenever an object property change,
Change detection will run on its bounded change detectorand down
If we like to effect its parent change detector we need events
ImmutableJs (cont.)
Immutable objects cannot be internally changed once created To “change” Immutable object we need to create a new one By that way we can easily “undo” changes ImmutableJs enables as to create this immutable objects
ImmutableJs Demo
Manually control change detection
At the component constructor we can get ChangeDetectorRef That’s acually the code generated for the component. Through this object we can control change detection
ChangeDetectorRef Demo
Summary
Change detection in Angular 2.0 is more efficient, transparent and easy to use
Its compiler generates change detector specifically to our components. Change detection goes top-down. OnPush strategy limits the change detection to the input members Immutable & observable objects enables as wider change detection We can also control change detection manually
Thank you!
@ranwahle https://blogs.microsoft.co.il/ranw [email protected] https://www.linkedin.com/in/ranwahle