BP164: Use ngZone.runOutsideAngular() to run heavy tasks outside of Angular's change detection cycle

Angular's change detection mechanism is a powerful feature that automatically updates the view when the data changes. However, it can also be a performance bottleneck when dealing with heavy tasks that don't require updating the view. By running these tasks outside of Angular's change detection cycle, we can improve the overall performance of our application.

The ngZone.runOutsideAngular() method allows us to run a function outside of Angular's change detection cycle. This means that any changes made within the function will not trigger a change detection cycle, which can be useful for heavy tasks such as data processing or network requests. Once the task is complete, we can use the ngZone.run() method to update the view with the new data.

import { Component, NgZone } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private ngZone: NgZone) {}

  heavyTask() {
    // run heavy task outside of Angular's change detection cycle
    this.ngZone.runOutsideAngular(() => {
      // perform heavy task here
    });

    // update view with new data
    this.ngZone.run(() => {
      // update view here
    });
  }
}

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play