javascript / expert
Snippet
High-Performance Event Handling with Zone-Bypass
For high-frequency events like scroll or mousemove, Angular's default change detection triggered by Zone.js can cause significant performance bottlenecks. By running the listener outside the Angular zone, we prevent change detection cycles for every event tick, only re-entering the zone when a state update is actually necessary.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component({...})export class ScrollComponent {constructor(private ngZone: NgZone, private el: ElementRef) {}ngOnInit() {this.ngZone.runOutsideAngular(() => {fromEvent(this.el.nativeElement, 'scroll').subscribe(() => {// Heavy calculation hereif (shouldUpdate) {this.ngZone.run(() => { this.state = 'updated'; });}});});}}
angular
Breakdown
1
this.ngZone.runOutsideAngular(() => {
Instructs Angular to execute the following block without triggering change detection for asynchronous tasks inside it.
2
fromEvent(this.el.nativeElement, 'scroll')
Creates an observable from the native scroll event, which would normally trigger Zone.js on every tick.
3
this.ngZone.run(() => { this.state = 'updated'; });
Explicitly re-enters the Angular zone to ensure that the UI is updated after the condition is met.