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.
1 2 3 4 5 6 7 8 9 10 11 |
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.
1 2 3 4 5 6 7 8 9 10 11 |
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 }); }); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.