我似乎无法弄清楚为什么我需要ngDoCheck生命周期钩子而不是简单的通知,特别是如何在其中编写代码与变化检测有关.我发现的大多数示例都显示了无用的示例,如此示例,具有一堆日志记录功能.
此外,在生成的类中,我没有看到它被用于除简单通知之外的其他内容:
conmponent/wrapper.ngfactory.js
Wrapper_AppComponent.prototype.ngDoCheck = function(view,el,throwOnChange) {
var self = this;
var changed = self._changed;
self._changed = false;
if (!throwOnChange) {
if (changed) {
jit_setBindingDebugInfoForChanges1(view.renderer,el,self._changes);
self._changes = {};
}
self.context.ngDoCheck(); <----------- this calls ngDoCheck on the component
but the result is not used
anywhere and no params are passed
}
return changed;
};
Run Code Online (Sandbox Code Playgroud) 我正试图理解这个ChangeDetectionStrategy.OnPush机制.
我从读数中得到的结论是,通过比较旧值和新值来进行变化检测.如果对象引用未更改,则该比较将返回false.
然而,似乎某些情况下绕过了"规则".你能解释一下这一切是如何运作的吗?
我不明白为什么即使我使用ChangeDetectionStrategy.OnPush和changeDetectorRef.detach()函数ngDoCheck一直被调用.我的应用程序中有数千个组件,如果从child2引发了一个事件(鼠标点击等),我想阻止child1的changeDetection.
这是一个掠夺者
如你所见,我有一个父组件
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
和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");
}
}
Run Code Online (Sandbox Code Playgroud)
如果我开始输入child1的输入,则调用child2的ngDoCheck函数.
想想有成千上万的孩子,它真的很慢...... …