From 796a928514670b72ca75013bf5063b35e3648b1e Mon Sep 17 00:00:00 2001 From: arturovt Date: Mon, 21 Apr 2025 18:09:22 +0300 Subject: [PATCH] fix(core): do not run change detection on global error events This commit wraps the `error` and `unhandledrejection` event listeners so they are installed outside of the Angular zone, because otherwise they trigger change detection whenever the event callbacks are invoked. --- packages/core/src/error_handler.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/core/src/error_handler.ts b/packages/core/src/error_handler.ts index dd2d8cdf0077..35f7249a3e8a 100644 --- a/packages/core/src/error_handler.ts +++ b/packages/core/src/error_handler.ts @@ -104,8 +104,19 @@ const globalErrorListeners = new InjectionToken(ngDevMode ? 'GlobalErrorLi e.preventDefault(); }; - window.addEventListener('unhandledrejection', rejectionListener); - window.addEventListener('error', errorListener); + const setupEventListeners = () => { + window.addEventListener('unhandledrejection', rejectionListener); + window.addEventListener('error', errorListener); + }; + + // Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in + // the scope of this functionality. + if (typeof Zone !== 'undefined') { + Zone.root.run(setupEventListeners); + } else { + setupEventListeners(); + } + inject(DestroyRef).onDestroy(() => { window.removeEventListener('error', errorListener); window.removeEventListener('unhandledrejection', rejectionListener);