What is Zone.js and how to use it in an Angular.js application?

Zone.js is built to handle change detection. Zone.js allows Angular to decide when the UI has to be refreshed. Everything goes smoothly when Zone.js is working properly but when something goes wrong with it it's really a frustrating situation so every developer should know some basics about Zone.js. Let’s see how it works. Zone.js fixes all common sync APIs like setTimeout, setInterval etc. to keep track of sync operations. Zone is a mechanism to interrupt and keep track of asynchronous work. In Angular every task runs in the Angular zone by default which is called NgZone. Zone.js has levels and hierarchies and you always start with the tp level Zone ie. the root zone. New Zones can be added by forking the root zone. New zones are created based on a ZoneSpec. ZoneSpec can include the name of the new child zone and various hook methods which can be used to intercept some task events. Zone.js can be deactivated if you want at the time of bootstrapping of an application by passing noop zone. If you want to control the changeDetection mechanism. Some times problems occur when change detection is triggered too often. You can inject the NgZone you get an API for deciding if an async operation should run inside or outside of the NgZone. Run OutsideAngular method can be used to run code outside NgZone. 


constructor(private ngZone: NgZone) {

  this.ngZone.runOutsideAngular(() => {

    // this will not trigger change detection

    setInterval(() => doSomething(), 100)

  });

}