NgZone Run Outside - Execute the “fn” functions asynchronously in Angular’s parent zone and returns value returned by the function.
Syntax- Ngzone.runOutsideAngular(fn:() => any): any
Example as,
import { 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
NgZone -
I hope you are enjoying with this post! Please share with you friends. Thank you!!