What are the methods of NgZone used to control change detection?

NgZone service provides a run() method that allows you to execute a function inside the angular zone. This function is used to execute third party APIs which are not handled by Zone and trigger change detection automatically at the correct time.

export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
ngOnInit() {
// use ngZone.run() to make the asynchronous operation in the angular zone
this.ngZone.run(() => {
someNewAsyncAPI(() => {
// update the data of the component
});
});
}
}

Whereas runOutsideAngular() method is used when you don't want to trigger change detection.

export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
ngOnInit() {
// Use this method when you know no data will be updated
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
// update component data and don't trigger change detection
});
});
}
}

May 22, 2022
384