【发布时间】:2017-06-17 17:04:06
【问题描述】:
我不明白为什么子组件的变更检测会在这种情况下运行:
import { Component, ChangeDetectionStrategy } from '@angular/core'
@Component({
selector: 'app-root',
template: `
<cmp [ticks]="ticks" (update)="onUpdate($event)"></cmp>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
ticks = 0;
onUpdate(event) {
console.log(this.ticks);
}
}
import { Component, ChangeDetectionStrategy, OnInit, Input, Output, EventEmitter, OnChanges } from '@angular/core';
@Component({
selector: 'cmp',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Number of ticks: {{ticks}}</p>
`
})
export class CmpComponent implements OnInit, OnChanges {
@Input('ticks') ticks: number;
@Output() update: EventEmitter<number> = new EventEmitter();
ngOnInit() {
setInterval(() => {
this.ticks++;
this.update.emit(this.ticks);
}, 1000);
}
ngOnChanges() {
console.log('changed');
}
}
当我运行时,子视图中的“滴答数”会更新。
当我在父级中删除监听事件时,它不会更新视图。
我的理解如下:
由于父级实现了 OnPush 策略,它在侦听从子级发出的事件时触发更改检测。在接收到事件时,它不会改变 'tick',因此子组件的 @Input() 不会更新。然而,也实现 OnPush 策略的子组件更新了它的视图。因此,它的行为就好像它的 @Input 发生了变化。
根据我的研究:
使用 OnPush 策略,如果出现以下情况,则会对组件进行更改检测:
- 在组件本身上接收到绑定事件。
- @Input() 已更新
- |异步管道收到一个事件
- “手动”调用了更改检测
这些似乎都不适用于子组件。
有什么解释吗?非常感激。
【问题讨论】:
标签: angular