angulardebuggingangular-ngzone

How to find which async action triggers ngZone (that lead to Change Detection)?


Any changes in the stack trace of updates always lead back to globalZoneAwareCallback. How do you find out what triggered the change?

In terms of debugging it's good to have a clear picture.


Solution

  • globalZoneAwareCallback is a function declared in zonejs for handling all event callbacks with capture=false. (btw, for capture=true there is globalZoneAwareCaptureCallback)

    It means that any event listener will first go through this method. That listener can be added on the page by Angular, by you or by any 3rd party library.

    There are many ways of how we can listen to browser events in Angular:

    Once you're within globalZoneAwareCallback you have access to all Zone tasks that should be triggered.

    Let's imagine we listen to click event on document.body:

    document.body.addEventListener('click', () => {
       // some code
    });
    

    Let's open Chrome dev tools to have a clear picture:

    enter image description here

    What we've just discovered:

    Let's consider another example and add click event using Angular way:

    <h2 class="title" (click)="test()">Hello {{name}}</h2>
    

    Once we click on that h2 element we should observe the following:

    enter image description here

    You might be surprised that now callback property didn't bring us to the test callback right away but rather we showed some wrapper from @angular/platform-browser package. And other cases also may differ but ZoneTask.source property is usually all you need in those cases because it shows you the root cause of the change.