Angular2 - Class - NgZone

官网文档说的足够用了

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.

对于不需要更新UI的异步操作, 用来优化性能

import {Component, View, NgZone} from 'angular2/core';
import {NgIf} from 'angular2/common';
@Component({
selector: 'ng-zone-demo'.
template: `
<h2>Demo: NgZone</h2>
<p>Progress: {{progress}}%</p>
<p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
<button (click)="processWithinAngularZone()">Process within Angular zone</button>
<button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
`,
directives: [NgIf]
})
export class NgZoneDemo {
progress: number = 0;
label: string;
constructor(private _ngZone: NgZone) {}
// Loop inside the Angular zone
// so the UI DOES refresh after each setTimeout cycle
processWithinAngularZone() {
this.label = 'inside';
this.progress = 0;
this._increaseProgress(() => console.log('Inside Done!'));
}
// Loop outside of the Angular zone
// so the UI DOES NOT refresh after each setTimeout cycle
processOutsideOfAngularZone() {
this.label = 'outside';
this.progress = 0;
this._ngZone.runOutsideAngular(() => {
this._increaseProgress(() => {
// reenter the Angular zone and display done
this._ngZone.run(() => {console.log('Outside Done!') });
}}));
}
_increaseProgress(doneCallback: () => void) {
this.progress += 1;
console.log(`Current progress: ${this.progress}%`);
if (this.progress < 100) {
window.setTimeout(() => this._increaseProgress(doneCallback)), 10)
} else {
doneCallback();
}
}
}

http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview

这个runOutsideAngular

/**
* Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
* the function.
*
* 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.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Angular zone.
*
* Use {@link #run} to reenter the Angular zone and do work that updates the application model.
*/
runOutsideAngular(fn: () => any): any {
if (this._disabled) {
return fn();
} else {
return this._mountZone.run(fn);
}
}

不做 change-detection 和 ChangeDetectionStrategy 里的detached 效果一样,但detached还是在zone里

/**
* `Detached` means that the change detector sub tree is not a part of the main tree and
* should be skipped.
*/
Detached