You can significantly improve Angular application performance by running high-frequency or non-essential code outside of the Angular Zone. This prevents Angular from triggering unnecessary change detection cycles every time an asynchronous task (like mousemove, scroll, or setTimeout) completes.
Core Concept: NgZone
Angular uses NgZone to wrap asynchronous APIs (XHR, setTimeout, user events). When an asynchronous task finishes, NgZone notifies Angular to run change detection. For high-frequency events like mousemove, this can lead to excessive CPU usage and dropped frames if the application has many components or complex templates.
Key Methods
NgZone.runOutsideAngular(callback): Executes the provided callback function outside of Angular's zone. Change detection will not be triggered when tasks inside this callback complete.NgZone.run(callback): Executes the provided callback function inside the Angular zone, ensuring that change detection is triggered once the callback finishes. This is useful for synchronizing the application state with the UI after a period of running outside the zone.
// Concept overview
// 1. Use runOutsideAngular for high-frequency events to avoid change detection.
// 2. Use run to bring execution back into the zone to sync state and trigger change detection.