前言:在模板中有實(shí)時(shí)獲取一個(gè)變量,模板中就頻繁的更新顯示。那么頻繁的變動(dòng)將造成性能損耗孵户。
或者在雙向綁定時(shí),異步事件的發(fā)生會(huì)導(dǎo)致組件中的數(shù)據(jù)變化腊尚,但是你想要適當(dāng)時(shí)機(jī)在改變模板顯示吨拗。
NgZone
NgZone是基于Zone來(lái)實(shí)現(xiàn)的,NgZone從Zone中fork了一份實(shí)例,是Zone派生出的一個(gè)子Zone,在Angular環(huán)境內(nèi)注冊(cè)的異步事件都運(yùn)行在這個(gè)子Zone上.
在Angular源碼中满哪,有一個(gè)ApplicationRef類(lèi),其作用是用來(lái)監(jiān)聽(tīng)ngZone中的onTurnDone事件劝篷,不論何時(shí)只要觸發(fā)這個(gè)事件哨鸭,那么將會(huì)執(zhí)行
一個(gè)tick()方法用來(lái)告訴Angular去執(zhí)行變化監(jiān)測(cè)。
// very simplified version of actual source
class ApplicationRef {
changeDetectorRefs:ChangeDetectorRef[] = [];
constructor(private zone: NgZone) {
this.zone.onTurnDone
.subscribe(() => this.zone.run(() => this.tick());
}
tick() {
this.changeDetectorRefs
.forEach((ref) => ref.detectChanges());
}
}
知道了Angular環(huán)境內(nèi)注冊(cè)的異步事件都運(yùn)行在這個(gè)NgZone上.下面使用一下runOutsideAngular方法
下面是一個(gè)DEMO
import {Component, NgZone} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: '<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>
',
})
export class AppComponent {
progress: number = 0;
label: string;
constructor(private _ngZone: NgZone) {}
processWithinAngularZone() {
this.label = 'inside';
this.progress = 0;
this._increaseProgress(() => console.log('Inside Done!'));
}
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();
}
}
}
點(diǎn)擊Process within Angular zone會(huì)因?yàn)殡p向綁定Progress會(huì)從1%持續(xù)變到100%.
而點(diǎn)擊Process outside of Angular zone 只會(huì)顯示1%直接到100%.
結(jié)論
runOutsideAngular() 使你的上下文不會(huì)觸發(fā)Angular跟蹤變化娇妓。 如果你想繼續(xù)跟蹤變化像鸡,使用run()方法即可讓Angular重新跟蹤變化。