Reactive Angular

Going zone-less

Zone.js

"Zones are a sort of execution context that allows us to hook into our asynchronous tasks"

Pascal Precht

Brian Ford - Zones

NG-Conf 2014

Articles by Pascal Precht:

Change Detection in Angular

Problems with Zone.js and Angular's CD

  • CD is triggered bottom to top and top to bottom by default
  • Can introduce performance issues with large applications
  • AsyncPipe relies on Zone.js

Problems with Zone.js and Angular's CD

  • One "change" (e.g. button click) triggers one change detection cycle
  • Multiple fast changes can result in low performance from many CD cycles running one after the other
  • The solution is coalescing of events

Solution #1 (?)

Solution #1 (?)

ChangeDetection.OnPush

CD is triggered when:

  • the input reference has changed
  • the component or one of its children triggers an event handler
  • change detection is triggered manually
  • an observable linked to the template via the async pipe emits a new value
    ---
  • 3rd-party components could have Default strategy - problem

Solution #2 (?)

Disable NgZone entirely or detach components

// polyfills.ts
import 'zone.js/dist/zone';

// main.ts
platformBrowserDynamic().bootstrapModule(
  AppModule, 
  { ngZone: 'noop' }
).catch(err => console.log(err));
  • trigger e.g. ChangeDetectionRef #detectChanges manually
constructor(private ref: ChangeDetectorRef) {
  ref.detach();
  setInterval(() => {
    this.ref.detectChanges(); 
  }, 10 * 1000);
}
  • manage detaching-attaching components
  • still trigger #detectChanges manually

Solution #3

DEMO

Thank you!

✋😎

@kajetansw

kajetan.dev

Reactive extensions for creating zone-less Angular applications

By Kajetan Świątek

Reactive extensions for creating zone-less Angular applications

  • 131