component lifecycle hooks in angular 2.0
TRANSCRIPT
Component lifecycle Hooks
Eyal Vardi
Site: http://ng-course.org
Blog: eyalVardi.wordpress.com
Agenda Lifecycle Hooks ngZone The ChangeDetector DoCheck & XXXDiffers
Data Binding
DOMData
UI Events
Timers
Communication
Bindings
Async Events Data Manipulations Dynamics DOM
Triggers
Angular 1.x Data Binding
<!-- Expressions --> Please type your name : {{name}}
<!-- Directives & Data Binding -->
Name: <input ng-model="name" value="..." />
Template
name : Scope valu
e
elm.bind('keydown', … )
$scope.$watch('name', … )
Directive
$apply$rootScope
Data Binding Performance F = Screen update frequency. Q = Data change detector quantity.
F x Q = Time
NgZone
NgZone What can change state in our
applications? XMLHttpRequests Timers Events
Zone override this methods: XMLHttpRequest setTimeout setInterval addEventListener removeEventListener
Application Tick Invoke tick() method to explicitly process
change detection and its side-effects.tick(): void { if (this._runningTick) { throw new BaseException("ApplicationRef.tick is called recursively"); } var s = ApplicationRef_._tickScope(); try { this._runningTick = true; this._changeDetectorRefs.forEach((detector) =>
detector.detectChanges()); if (this._enforceNoNewChanges) { this._changeDetectorRefs .forEach((detector) => detector.checkNoChanges()); } } finally { this._runningTick = false; wtfLeave(s); }}
NgZone run() runOutsideAngular()
ngZone Events: onTurnStart() onTurnDone() onEventDone()
NgZone Demo
The Loop Problem
Change Detector
Change Detection Strategy Describes within the change detector which
strategy will be used the next time change detection is triggered.
Work on the template.
CheckAlway
s Default
CheckOnce OnPush
Checked Detached
ChangeDetectorRef Controls change detection. detach() reattach()
markForCheck()
detectChanges() checkNoChanges()
constructor(private ref:
ChangeDetectorRef) {
ref.detach();
setInterval(() => {
this.ref.detectChanges();
}, 5000);
}
Doing a local check every five
seconds.
KeyValueDiffers A repository of different Map diffing
strategies. Used by NgClass, NgStyle, and others.class Component{ data:any = {}; _differ: KeyValueDiffer;
constructor(private _differs:KeyValueDiffers){ this._differ = this._differs.find(this.data).create(null); }
ngDoCheck() { var changes = this._differ.diff(this.data); if (changes) { changes.forEachAddedItem ((r) => { log(r.key,r.currentValue); }); changes.forEachChangedItem((r) => { log(r.key,r.currentValue); }); changes.forEachRemovedItem((r) => { log(r.key,r.currentValue); }); } }}
IterableDiffers A repository of different iterable diffing
strategies. Used by NgFor, NgClass, and others.
class Component{ data:any = []; _differ: IterableDiffer;
constructor(private _differs:IterableDiffers){ this._differ = this._differs.find(this.data).create(null); } ngDoCheck() { var changes = this._differ.diff(this.data); if (changes) { changes.forEachAddedItem ((r) => { this.addData.push(r)}); changes.forEachRemovedItem((r) => { this.removeData.push(r)}); } }}
Change Detector Options
Properties OnChanges DoCheck
Data Changes: Detach & Reattach Detach &
MarkForCheck Detach &
DetectChanges
Refresh:
Lifecycle Hooks
Component Node
Component Directive
TemplateContent
*
* *
DOM Element
<component1 directive1> <component2> This is content. </component2></component1>
(component1)
(component2)
(directive1)
Tree ComponentsApp
Component1
Component2
Directive1
Component3
loading
Template Content
<app>Loading</app>
<div> <component1 directive1="{{name}}"> <component2> This is content. </component2> </component1></div>
<div> <h4>{{name}}</h4> <ng-content /></div>
This is content
<div> <h4>{{name}}</h4> <ng-content /></div>
Lifecycle Hooks Angular calls lifecycle hook methods on
directives and components as it creates, changes, and destroys them.
Creates: OnInit AfterContentInit AfterViewInit
Changes: DoCheck OnChanges AfterContentChecked AfterViewChecked
Destroys: OnDestroy
Hooks Order
Component
TemplateContent
* *
OnChangesOnInit
AfterContentInitAfterContentChecked
AfterViewInitAfterViewChecked
DoCheck
Hooks Order
Component
TemplateContent
* *
OnChangesOnInit
AfterContentInitAfterContentChecked
AfterViewInitAfterViewChecked
DoCheck
1
2
3
4
5
6
7
Hooks OrderHooks Descriptions
ngOnChanges Called when an input or output binding value changes
ngOnInit After the first ngOnChanges
ngDoCheck Developer's custom change detection
ngAfterContentInit After component content initialized
ngAfterContentChecked After every check of component content
ngAfterViewInit After component's view(s) are initialized
ngAfterViewChecked After every check of a component's view(s)
ngOnDestroy Just before the directive is destroyed
Creation Hooks Order in a Tree
Component
Directive
TemplateContent
*
*
DOM Element
ConstructorngOnInit
Constructor
*
Constructor
ConstructorngOnInitngOnInit
ngOnInit
ngAfterContentInitngAfterContentChecked
ngAfterContentInitngAfterContentChecked
ngAfterContentInitngAfterContentChecked
ngAfterContentInitngAfterContentChecked
AfterViewInitAfterViewChecked
AfterViewInitAfterViewChecked
AfterViewInitAfterViewChecked
AfterViewInitAfterViewChecked
Changing Hooks Order in Tree
Component
Directive
TemplateContent
*
*
DOM Element
*
ngAfterContentChecked
ngAfterContentCheckedngAfterContentChecked
ngAfterContentChecked
AfterViewCheckedAfterViewChecked
AfterViewCheckedAfterViewChecked
Thankseyalvardi.wordpress.com
Eyal Vardi
Site: http://ng-course.org
Blog: eyalVardi.wordpress.com