Angular 5 - 如何将更改检测仅限于组件范围?

Pol*_*zny 5 javascript angular2-changedetection angular angular5

如何配置 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,请查看父组件 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>
Run Code Online (Sandbox Code Playgroud)

someBindingProperty是一个吸气剂:

get someBindingProperty() {
  this.bindingTimer++;
  return this.bindingTimer;
}
Run Code Online (Sandbox Code Playgroud)

问题:当 TimerComponent 增加值时,会触发整个应用程序的更改检测。是否可以仅在组件和子组件内触发更改检测?

注意:如果我添加到 TimerComponent:

changeDetection: ChangeDetectionStrategy.OnPush
Run Code Online (Sandbox Code Playgroud)

然后在此组件中不会检测到更改,但仍会为整个应用程序触发更改检测。所以这不是一个解决方案。

小智 1

临时禁用更改检测的另一个选项 ChangeDetectorRef

enabled = true;  
constructor(private ref: ChangeDetectorRef)

toggleChangeDetection() {
  if (this.enabled) 
  {
    this.enabled = false;
    this.ref.detach();
  }
  else {
    this.enabled = true;
    this.ref.reattach();
}
Run Code Online (Sandbox Code Playgroud)