When to use Ngzone in ANGULAR
Every JavaScript framework has its own way to handle the change detection. i.e. When to update the UI.
Considering the Angular framework, it uses Zone.js.
Open your package.json file in angular project and you will see zone.js.

Zone.js is an execution context for tracking and intercepting async operations like: DOM events (click, keydown, keyup, etc), setTimeout, setInterval. XMLHttpRequests etc. So, without zone.js, we don’t get any change detection, so we don’t get any of the nice UI updates that we’d expect.
But by default, angular can’t detect changes made by async callbacks of third-party libraries because “they are not in angular’s zone”. In this scenario, you can use NgZone service.
NgZone is just an injectable wrapper angular service around Zone.js’s API for executing work inside or outside of the Angular zone.
The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don’t require UI updates. Such tasks can be taken out from angular zone via runOutsideAngular method and if needed, these tasks can reenter the Angular zone via run method.
NgZone gives you back control of your code’s execution. There are two relevant methods in NgZone – run and runOutsideAngular:
- runOutsideAngular runs a given function outside the angular zone, meaning its code won’t trigger change detection.
- run runs a given function inside the angular zone.
How to use NgZone in angular.
Step 1: Import the NgZone service from angular core.

Step 2: Inject the service inside component constructor.

Step 3: Now use in methods


Code Sample:
Here this code get the users based on google location. Since we call the external google library inside angular, relevant change detection will not occur.
GetUserByLocation() {
googleSdk.getLocations(location => this.getUsers());
}
getUsers(): void {
this.userService.getUsers().subscribe(e => {
this.user = e;
});
}
But using ngzone run method, we can make sure all detection happens inside angular
GetUserByLocation() {
googleSdk.getLocations(location => this.ngZone.run(() => this.getUsers()));
}
getUsers(): void {
this.userService.getUsers().subscribe(e => {
this.user = e;
});
}
Thanks for reading.
- Posted by admin
- On December 6, 2019
- 0 Comment