Tag Archives: $scope.$apply in angular 2 and beyond

ngZone === $scope.$apply(). What is equivalent of $scope.$apply() in angular 2 and beyond…..

ngZone is an injectable service for executing work inside or outside of the Angular zone. The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don’t require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks can reenter the Angular zone via run.

In Angular 2, change detection is automatic as opposed to Angular 1 that applys the change detection with the help of methods like $scope.$watch() and $scope.$digest().

Under the hood, Angular 2 uses something called Zones. In a nutshell, Zone.js intercepts all of the asynchronous APIs in the browser by monkey patching them.

Monkey patching is a technique to override, extend or even suppress the default behavior of a code segment without changing its source code. So when we call something like setTimeout — Angular 2 knows that and can trigger change detection and decide if she needs to update the DOM because setTimeout() is monkey patched.

Angular 2 gives us the ability to escape from change detection with the help of the ngZone service that exposes the runOutsideAngular method. Running functions via runOutsideAngular allows you to escape Angular’s zone and do work that doesn’t trigger Angular change-detection or is subject to Angular’s error handling.

We need to pass a function to this method and any future tasks scheduled from within this function will continue executing from outside of the Angular zone.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor(private ngZoneService: NgZone){
    this.ngZoneService.runOutsideAngular(()=>{
      //Execute all Your code over here which needs to be executed 
      // outside of angular context
      // ...
      // ...
      // ...
      // ...
      // ...

      //Reenter 
      this,ngZoneService.run(()=>{
          console.log("Reenetering angular context....")
      });

    });
  }
}

 

Advertisements