zoukankan      html  css  js  c++  java
  • [Angular] Zones and NgZone

    NgZone, Angular uses it to profiling all the async actions such as setTimeout, http request and animation.

    For example if you dealing with heavy oprations for hundreds of times, you might want it run outside Angular Zone, so it won't trgger change detection hundreds of times.

    import { Component, OnInit, DoCheck, NgZone } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>
          Counter: {{ counter }}
        </div>
      `
    })
    export class AppComponent implements OnInit, DoCheck {
      counter = 0;
      constructor(
        private zone: NgZone
      ) {}
      ngOnInit() {
        this.zone.runOutsideAngular(() => {
          for (let i = 0; i < 100; i++) {
            setTimeout(() => this.counter++);
          }
          this.zone.run(() => {
            setTimeout(() => this.counter = this.counter, 1000);
          });
        });
      }
      ngDoCheck() {
        console.log('Change detection has been run!');
      }
    }

    To notice that, the operation puts inside 'runOutsideAngular' should be async opreation. Otherwise there is no effect. Now you can think that Angular won't update our 'counter' if we run outside Angular. 

    So if we resume (trigger change detection) again, we can do:

          this.zone.run(() => {
            setTimeout(() => this.counter = this.counter, 1000);
          });

      

  • 相关阅读:
    每日一剂 14-6-6
    每日一剂 14-6-5
    每日一剂 14-6-4
    每日一剂 14-5-30
    Maven清理 .lastUpdated文件
    Docker 将项目做成镜像部署在docker中
    Docker 镜像拷贝到 正式环境运行
    Docker 安装 Tomcat
    Docker 安装 ActiveMq
    Docker 安装 nginx
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6843681.html
Copyright © 2011-2022 走看看