Angular 2 runs inside of its own special zone called NgZone and this special zone extends the basic functionality of a zone to facilitate change detection.
It is Running inside a zone allows to detect when asynchronous tasks.
If you change or update your internal application code or view and it is detecting the applications changes with help of NgZone.
Example 1 - We use NgZone to trigger change detection asimport { Component, NgZone} from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpModule, Http } from '@angular/http'; import { UserService } from '../service/user.service'; import { AppGlobals } from '../../shared/app.globals'; @Component({ selector: 'user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'], providers: [UserService, AppGlobals] }) export class UserComponent { //USERS DECLARATIONS. users = []; label: string; counter: number = 0; //USER COMPONENT CONSTRUCTOR. constructor(private _userService: UserService, private _global: AppGlobals, private _ngZone: NgZone) { } //GET USERS SERVICE ON PAGE LOAD and BIND UI GRID. ngOnInit() { this._userService.getAPIUsers(this._global.baseAPIUrl + 'users/hadley/orgs').subscribe(data => this.users = data); this._userService.getAppUsers(this._global.baseAppUrl + 'api/User/GetUsers').subscribe(data => console.log(data)); } // Loop inside the Angular zone. // The UI will refresh after each setTimeout cycle. insideOfAngularZone() { this.label = 'inside loop'; this.counter = 0; this._increaseCounter(() => alert('Inside loop completed.')); } // Loop outside of the Angular zone. // The UI will not refresh after each setTimeout cycle. outsideOfAngularZone() { this.label = 'outside loop'; this.counter = 0; this._ngZone.runOutsideAngular(() => { this._increaseCounter(() => { this._ngZone.run(() => { alert('Outside loop completed.'); }); }); }); } _increaseCounter(doCallback: () => void) { this.counter += 2; if (this.counter <= 1000) { window.setTimeout(() => { this._increaseCounter(doCallback); }, 100); } else { doCallback(); } } } //END BEGIN - USER-COMPONENT
Example 2 -We use NgZone to trigger change detection as,
constructor(_ngZone:NgZone) { window.onresize = (e) => { _ngZone.run(() => { this.width = window.innerWidth; this.height = window.innerHeight; }); }; }
import {ChangeDetectorRef} from '@angular2/core' export class SideNav { innerWidth: number; constructor(private window: Window, private _cdr: ChangeDetectorRef){ let getWindow = () => { return window.innerWidth; }; window.onresize = () => { this.innerWidth = getWindow(); this._cdr.detectChanges(); //running change detection manually! }; } }
I hope you are enjoying with this post! Please share with you friends. Thank you!!