Angular : NgZone (Optimizing angular Performance)

Ashish
4 min readJan 11, 2021

--

Do you know how change detection works in angular ?? ..

When any of the asynchronous task is started or finished , it will notifies the angular that a change has been done, so that the DOM tree get updated to render the desired results. The asynchronous tasks includes things like XHR calls, setTimeout() and pretty much all user events like click, submit , mouseup …… etc.

We need not worry about the change detection , because angular will do the complete process with the help of Zones.

To get idea of zones in angular follow this link https://angular.io/guide/zone

But is it a good idea to tell angular every time when we perform some asynchronous task ?

Definitely NOT, this will effect the performance of your application . The following snippet will show you how :

I have made small dummy app . The app component will consist of another component named as app-verify ,a div and a button with a click event, which decrease the timer when we click on it. The complete code is given below :

The verify component is just a dummy component, it consist of an angular life cycle hook ngDoCheck which is executed each time when the change detection occurs.

The output of the above app will look like this :

Whenever I click on SET COUNTDOWN button, the count will decrease until it becomes zero .Let’s give it a try , I just click on the button and what I see in console, that the console statement which is present in ngDoCheck is executed each time whenever our count decreases. Why ??..

But why this is not the behavior you want in your application because you know that the change is only done for app component and it’s not related to the verify component , we don’t want verify component to detect those changes because this will affect our application performance. How can we control that ??…

Here comes the NgZone to rescue, using this you can tell the angular to execute the code and does not tell about the change detection to the whole application. It’s easy to implement , just add entry to the constructors and. put the code(which is deteriorate your app performance) in runOutsideAngular(()=>{}). You can also see the example below :

You have to use NgZone Api available in angular, and put you code inside runOutsideAngular(()=>{}).

Now it’s time to see our result. Let’s see what happened now:

Great😀… , now we don’t have any console statement , when our counter changes, the code is executed outside of angular zone. So change detection will not run every time our counter changes. But you still see a console message🤨!… Because I told you that our change detection works when we perform any async task , click is an async task, that’s why we have that one message 👍.

Press Follow 👈 for More Interesting Topics.

--

--