【问题标题】:Angular 2 - how to Prevent Change DetectionAngular 2 - 如何防止更改检测
【发布时间】:2018-04-18 06:00:15
【问题描述】:

我想避免更改检测,我尝试了一种方法,但我想在角度概念之外使用

plunkr sample *此链接有我的 plunkr 示例,我尝试了一种方法来避免创建微任务的更改检测 *

onClick() {
    this.num++;
    
    this.cdRef.detach();
    this.ngZone.onMicrotaskEmpty.first().subscribe(() => {
      this.cdRef.reattach();
    });
  }

我提到了这个问题,但我找不到我的解决方案 relative question

【问题讨论】:

  • 为什么需要阻止变更检测?
  • 在我的项目中出现性能不足的问题,所以我的 frd 建议我避免更改检测
  • 您可以在组件元数据中将组件更改检测设置为OnPush。你试过吗?
  • 你能看看这个 plunkr。 plnkr.co/edit/6Ea2PFW9a186TBQxES1r?p=preview
  • 我只是创建了微任务以避免更改检测,它工作正常

标签: angular angular2-changedetection


【解决方案1】:

 onClick() {
    debugger
    this._ngZone.runOutsideAngular(() => {
      // this.num++
      setTimeout(()=>this.num = 5);    
      });
  }

我使用这段代码而不是使用微任务方法,它工作正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2020-08-19
    • 2017-09-18
    • 2018-07-24
    相关资源
    最近更新 更多