Web Programming TutorialsLearn About the Role of Zones in Angular 2

Learn About the Role of Zones in Angular 2

Zones

In this article, we are going to discuss and learn about the role of Zones played in Angular 2. Zones are a sort of execution context that allows us to hook into our asynchronous tasks.

Zones in Angular 2.0
Zones are a great fit for Angular 2 as they help provide whatever is required by Angular in order to perform change detection in the applications. Application state change is caused by the following things.

  • Events – these are the user events such as click, change, input, submit, etc.
  • XMLHttpRequests – Such thing occurs when we fetch data from a remote service.
  • Timers – when we use timer methods such as setTimeout (), setInterval (), etc.

All of these three things are asynchronous in nature. These things when triggered could change the application status. Let us understand zones in Angular 2.0 in detail with the help of the following example.

Zones in Angular 2.0 Demonstration
Say for example, we have an Angular component that executes a handler when we click a button. Such demonstration will show the execution inside Angular’s zone in order to ensure that the framework is notified when an event has triggered. In the same example, we are going to demonstrate how the code can be executed outside Angular’s zone, which refrains the GUI from getting updated after every event is triggered.

Angular 2.0 coding for Tabs Component
app/main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './Module';
platformBrowserDynamic().bootstrapModule(AppModule);

Explanation of Code:
The above main.ts file is used to Bootstrap the angular 2.0 app that uses the root component from the NgModule.
app/Module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './Component';
import { NgZoneDemoComponent } from './ng-zone.Component';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, NgZoneDemoComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Explanation of Code:
The root App Module typescript file is present in the app package. Here, we are importing the NgModule, BrowserModule, NgZoneDemoComponent, and AppComponent classes as shown above. The @NgModule decorator is declared here that has imports, declaration classes and bootstrap class to start the app.
app/Component.ts

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

@Component({
  selector: 'my-zone-app',
  templateUrl: 'resource/app.component.html'
})
export class AppComponent { 
	title = "Zones in Angular 2.0";
}

Explanation of Code:
Here, we are declaring the component with selector as ‘my-zone-app’ and templateUrl as ‘resource/app-component.html’ that has the required HTML code to render on the web page. The controller class ‘AppComponent’ has a title variable with the value as “Zones in Angular 2.0”.
resource/app.component.html

<div align="center">
<h2>{{title}}</h2>
    
<p>
1. <strong>inside</strong> Angular's zone: This demo will show how code is executed inside the Angular's zone to
ensure the framework is notified when an event has triggered. <br>
2. <strong>outside</strong> Angular's zone: It also demonstrates how code can be executed, which refrain the UI to from update after every event tick.
</p>

<p>Please click on the buttons to view the code in action (explained above).</p>
<hr>
<br>
<ng-zone-demonstration></ng-zone-demonstration>
</div>
<hr>
<center>Zones in Angular 2.0</center>

Explanation of Code:
Here, we are using the tag as ‘ng-zone-demonstration’ where we are calling the ‘ng-zone.Component.ts’ app logic to process the code inside as well as outside of the Angular zone. Rest are the supporting text fields which will be displayed on the web page.
app/ng-zone.Component.ts

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

@Component({
  selector: 'ng-zone-demonstration',
  templateUrl: 'resource/ng-zone.Component.html'
})
export class NgZoneDemoComponent {
  progress: number = 0;
  label: string;
  
  constructor(private _ngZone: NgZone) {}
  
  // Loop inside the Angular zone. Therefore, the UI does refresh after each setTimeout cycle
  withinAngularZoneProcess() {
       this.label = 'inside';
       this.progress = 0;
       this._increaseProgressBar(() => console.log('Inside Processing Completed!'));
  }

  // Loop outside of the Angular zone. Therefore, the UI does not refresh after each setTimeout cycle 
  outsideOfAngularZoneProcess() {
        this.label = 'outside';
        this.progress = 0;
        this._ngZone.runOutsideAngular(() => {
        this._increaseProgressBar(() => {
        this._ngZone.run(() => { console.log('Outside Processing Completed!') });
      
      });
    });
  }
  
  
  _increaseProgressBar(doneCallback: () => void) {
    this.progress += 2;
    console.log(` Here is the current progress: ${this.progress}%`);
    
    if (this.progress < 1000) {
      window.setTimeout(() => {
        this._increaseProgressBar(doneCallback);
      }, 10);
    } else {
      doneCallback();
    }
  }  
}

Explanation of Code:
In the ‘app.component.html’ file we have used the tag ‘ng-zone-demonstration’ which is nothing but the component selector that has underlying ng zone logic defined in the template file ‘resource/ng-zone.Component.html’ as shown below. It has the controller class ‘NgZoneDemoComponent’, where we are declaring the variables progress as number type and label as string type. The constructor used here accepts the instance of NgZone as_ngZone. NgZone is nothing but a forked zone that extends its API and adds some additional functionality to its execution context. It adds to the API the custom events to which we can subscribe. Later, we are defining two methods i.e. ‘withinAngularZoneProcess ()’ to process the code within the angular zone and ‘outsideOfAngularZoneProcess ()’ to process the code outside the angular zone as shown above. These methods are called on the button click events as specified in the template file ‘ng-zone.Component.html’ as explained below.
resource/ng-zone.Component.html

<p>Progress: {{progress}}%</p>
    <p *ngIf="progress >= 1000">Done processing {{label}} of the Angular zone!</p>
    
    <button (click)="withinAngularZoneProcess()">Process within the Angular zone</button>
    <button (click)="outsideOfAngularZoneProcess()">Process outside of the Angular zone</button>

Explanation of Code:
It is the actual HTML code associated with the template file of ‘app/ng-zone.Component.ts’. It has two buttons with the name as ‘Process within the Angular zone’ and ‘Process outside of the Angular zone’. Each of these buttons has the click event associated with the action which calls the methods ‘withinAngularZoneProcess ()’ or ‘outsideOfAngularZoneProcess ()’ respectively as shown above. The *ngIf condition is used to evaluate the count associated with the progress number type variable and display the text ‘Done processing {{label}} of the Angular zone!’ when it exceeds the value of 1000.
assets/styles.css

h2 {
	color: #369;
	font-family: Georgia, Helvetica, sans-serif;
	font-size: 250%;
}

h3 {
	color: #669;
	font-family: Georgia, Helvetica, sans-serif;
	font-size: 250%;
}

p {
	color: #969;
	font-family: Georgia, Helvetica, sans-serif;
	font-size: 100%;
}

body {
	margin: 2em;
}

Explanation of Code:
It is the stylesheet used to style the text on the web page of the app.
Index.html

<html>
<head>
<title>Zones in Angular 2.0</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/styles.css">
<!-- 1. Load libraries -->
<!-- Poly-fills for the older browsers -->
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->

<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
      System.import('app').catch(
    		  function(err){ 
    			  console.error(err); 
    			  }
    		  );
</script>
</head>
<!-- 3. Display the application -->
<body>
	 <my-zone-app>Please wait...</my-zone-app>
</body>
</html>

Explanation of Code:
It is the ‘index.html’ file that has the ‘my-zone-app’ tag in its body section i.e. selector of ‘Component’ to load and display the complete application. Here, we are including all the paths for the scripts which are required for the Angular 2.0 build as shown above.

Output
When we run the above angular 2.0 app for zone components by executing the command ‘npm start’ on command line that has pointer to the application’s root directory ‘my-zone-component-app’ then we will observe the following output.
Zones Component

Source code for the zone component app in Angular 2.0

Conclusion: –
In this chapter, we developed a zone component app in Angular 2.0 to demonstrate the processing inside as well as outside of the Angular zone.

1 COMMENT

  1. Nice blog! Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your next write ups thank you once again. Please also come and visit into my website at

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -