簡體   English   中英

Angular 5 - 如何將變化檢測限制在組件 scope 上?

[英]Angular 5 - how to limit change detection only to component scope?

如何配置 Angular 組件不觸發整個應用程序的變化檢測,而只觸發組件本身及其子組件?

工作示例: https://stackblitz.com/edit/angular-irc-starter-4txpbu?file=app%2Ftimer%2Ftimer.component.ts

有一個每秒增加一個值的計數器。 它是 TimerComponent 並且按預期工作 - 值每秒增加和更新。

@Component({
  selector: 'app-timer',
  template: `{{value}}`
})
export class TimerComponent implements OnInit {
  value: number = 0;
  ngOnInit() {
    setInterval(() => this.value++, 1000);
  }
}

但是,看看父組件AppComponent。

<h3>Internal timer:</h3>
<p>Should not perform change detection for the whole app</p>
<app-timer></app-timer>

<h3>External binding</h3>
<p>Should not be updated after timer changes</p>
<p>{{someBindingProperty}}</p>

someBindingProperty是一個吸氣劑:

get someBindingProperty() {
  this.bindingTimer++;
  return this.bindingTimer;
}

問題:當 TimerComponent 增加值時,會觸發整個應用程序的變化檢測。 是否可以只在組件和子組件中觸發變化檢測?

注意:如果我添加到 TimerComponent:

changeDetection: ChangeDetectionStrategy.OnPush

然后在此組件中未檢測到更改,但仍會為整個應用程序觸發更改檢測。 所以這不是解決方案。

臨時禁用更改檢測ChangeDetectorRef的另一個選項

enabled = true;  
constructor(private ref: ChangeDetectorRef)

toggleChangeDetection() {
  if (this.enabled) 
  {
    this.enabled = false;
    this.ref.detach();
  }
  else {
    this.enabled = true;
    this.ref.reattach();
}

您可以在 angular 區域之外為您的計時器運行間隔,並在每次計時器值增加時調用ChangeDetectorRef.detectChanges

this.ngZone.runOutsideAngular(() => {
  setInterval(() => {
    this.timer++;
    this.cdr.detectChanges();
  }, 1000);
});

ChangeDetectorRef.detectChanges僅檢測此視圖及其子視圖的更改。

我試了一下,使用Angular DevTools 探查器,您可以看到根組件 (AppComponent) 和同級組件 (SthWithDefaultCdComponent) 都沒有被檢查。 定時器組件是否使用 OnPush 策略沒有區別。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM