Angular 8 动态加载组件显示 NgZone runOutsideAngular

前言:在模板中有实时获取一个变量,模板中就频繁的更新显示。那么频繁的变动将造成性能损耗。
或者在双向绑定时,异步事件的发生会导致组件中的数据变化,但是你想要适当时机在改变模板显示。

NgZone

NgZone是基于Zone来实现的,NgZone从Zone中fork了一份实例,是Zone派生出的一个子Zone,在Angular环境内注册的异步事件都运行在这个子Zone上.

在Angular源码中,有一个ApplicationRef类,其作用是用来监听ngZone中的onTurnDone事件,不论何时只要触发这个事件,那么将会执行
一个tick()方法用来告诉Angular去执行变化监测。

// 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环境内注册的异步事件都运行在这个NgZone上.下面使用一下runOutsideAngular方法

下面是一个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();
     }
   }
}

点击Process within Angular zone会因为双向绑定Progress会从1%持续变到100%.
而点击Process outside of Angular zone 只会显示1%直接到100%.

结论

runOutsideAngular() 使你的上下文不会触发Angular跟踪变化。 如果你想继续跟踪变化,使用run()方法即可让Angular重新跟踪变化。

哪里有不明确或者错误,欢迎给我留言!

我相信路飞最后一定会和女帝在一起的😊

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,079评论 19 139
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,671评论 8 265
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,159评论 1 32
  • 都说读万卷书不如行万里路,行万里路不如阅人无数,阅人无数不如名师指路,名师指路不如自己去悟,可是在大部分人看来,再...
    千千结_阅读 856评论 0 1
  • 才发现前面立下的flag都没有实现,人就是这样,周期性产生懒惰感觉。 我知道很难,我也很佩服自己。 最后一个寒假,...
    linkin_xiao阅读 163评论 0 0