【发布时间】:2018-01-18 19:56:26
【问题描述】:
我不明白为什么即使我使用 ChangeDetectionStrategy.OnPush 和 changeDetectorRef.detach() 函数 ngDoCheck 仍然被调用。 我的应用中有数千个组件,如果从 child2 引发事件(鼠标单击等),我想阻止 child1 的 changeDetection。
这是plunker
如你所见,我有一个父组件
@Component({
selector: 'my-app',
template: `
<app-child1 test="test"></app-child1>
<app-child2 test="test"></app-child2> `,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
test = 'test';
constructor() { }
ngDoCheck() {
console.log("### ngDoCheck app component");
}
}
和 2 个相同的孩子:
@Component({
selector: 'app-child1',
template: `<input type="text" [(ngModel)]="test" /><br/> `,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Child1Component implements OnInit {
@Input()
test: string;
constructor(public cd: ChangeDetectorRef) { }
ngAfterViewInit() {
console.log("###### DETACH child 1");
this.cd.detach();
}
ngDoCheck() {
console.log("### ngDoCheck child 1");
}
}
如果我开始在 child1 的输入中输入,就会调用 child2 的 ngDoCheck 函数。
想想有成千上万的孩子,它变得非常缓慢......
谢谢!
【问题讨论】:
-
我正在阅读这个blog.thoughtram.io/angular/2017/02/02/…,看起来我必须在子组件和父组件上调用 detach 方法,但是为什么呢?
标签: angular angular2-changedetection