Skip to content

Instantly share code, notes, and snippets.

@akshatamohanty
Last active May 23, 2018 05:30
Show Gist options
  • Select an option

  • Save akshatamohanty/6fa3189411d9413c7415052e5a32ffc4 to your computer and use it in GitHub Desktop.

Select an option

Save akshatamohanty/6fa3189411d9413c7415052e5a32ffc4 to your computer and use it in GitHub Desktop.
Optimized Change Detection in Angular Component
// https://pascalprecht.github.io/slides/angular-2-change-detection-explained/#/109
@Component()
class AnotherCmp {
notifier:Observable<any>;
constructor(private cd: ChangeDetectorRef) {}
ngOnInit() {
this.cd.detach();
this.notifier.subscribe((attach) => {
attach ? this.cd.reattach() : this.cd.detach();
});
}
}

When checkAndUpdateView function is triggered for a particular view it does the following operations in the specified order:

  • sets ViewState.firstCheck to true if a view is checked for the first time and to false if it was already checked before
  • checks and updates input properties on a child component/directive instance
  • updates child view change detection state (part of change detection strategy implementation)
  • runs change detection for the embedded views (repeats the steps in the list)
  • calls OnChanges lifecycle hook on a child component if bindings changed
  • calls OnInit and ngDoCheck on a child component (OnInit is called only during first check)
  • updates ContentChildren query list on a child view component instance
  • calls AfterContentInit and AfterContentChecked lifecycle hooks on child component instance (AfterContentInit is called only during first check)
  • updates DOM interpolations for the current view if properties on current view component instance changed
  • runs change detection for a child view (repeats the steps in this list)
  • updates ViewChildren query list on the current view component instance
  • calls AfterViewInit and AfterViewChecked lifecycle hooks on child component instance (AfterViewInit is called only during first check) disables checks for the current view (part of change detection strategy implementation)
  • There are few things to highlight based on the operations listed above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment