I got a bug in my angular project which finally resolved by wrapping my code into
this.zone.run(() => {/* my code here */});
as stated by this answer.
My previous understanding of zone
was that angular can't detect changes made by async callbacks
of third-party libraries because "they are not in angular's zone
". If I click on a button
, the event that gets triggered is not browser's native click
event but a custom (patched) click
event created by angular whose handler
runs in the zone
so angular is aware of the changes made by its callback handler.
But I could not understand by running router.navigate()
in third party callback create this problem (as indicated by this github issue). Isn't Router
a service
of angular itself? Why doesn't it automatically inform angular's zone
when called in third party callback
?
I got this problem by using router.navigate
within state reducer of NGXS.
My question is:
Can someone explain when exactly do I need to wrap my code in NgZone
?
Debugging for hours and realizing that my code is out of zone
context is tiresome.
In those cases, the NgZone service provides a run() method that allows you to execute a function inside the Angular zone. This function, and all asynchronous operations in that function, trigger change detection automatically at the correct time.
Angular 2 runs inside of its own special zone called NgZone and this special zone extends the basic functionality of a zone to facilitate change detection. It is Running inside a zone allows to detect when asynchronous tasks.
ngZone.runOutsideAngular() - this runs the code outside the angular zone.
Angular itself uses ngZone under the hood to detect the changes
So, if we have came out of angular zone, then to come back we use ngZone.run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With