0 day streak
javascript / expert
Snippet

Optimizing External Library Logic outside NgZone

NgZone (Zone.js) intercepts asynchronous operations to trigger change detection. Running high-frequency logic (like mouse moves or chart animations) inside 'runOutsideAngular' prevents unnecessary global change detection cycles, significantly improving application responsiveness when integrating with non-Angular libraries.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component({ ... })
export class ChartComponent implements OnInit {
constructor(private zone: NgZone, private el: ElementRef) {}
ngOnInit() {
this.zone.runOutsideAngular(() => {
// Third-party library doing heavy DOM manipulation or timers
const chart = new HeavyChartLibrary(this.el.nativeElement);
chart.on('render', () => {
console.log('Rendering...');
});
});
}
}
angular
Breakdown
1
this.zone.runOutsideAngular(() => { ... })
Executes the code block without triggering Angular's change detection mechanism.
2
new HeavyChartLibrary(...)
Ensures internal library timers/events don't wake up the whole app's UI check.