我有一个大型组件,我希望避免不必要的更改检测以提高性能。
我将 changeDetection: ChangeDetectionStrategy.OnPush
添加到 @Component
。
我想更新滚动元素的样式。不幸的是,每次我滚动该元素时,Angular 都会运行更改检测。
我尝试向 native 元素添加事件监听器以避免这种情况,但当我滚动时更改检测仍在再次运行:
@ViewChild('my_element') my_element_ref: ElementRef;
ngOnInit() {
this.my_element_ref.nativeElement.addEventListener('scroll', this.updateStyle);
}
ngAfterViewChecked() {
console.log('check');
}
即使 this.updateStyle
是空函数,ngAfterViewChecked
也会被调用。
但是,如果我注释掉 this.my_element_ref.nativeElement.addEventListener('scroll', this.onScroll)
,则不再调用 ngAfterViewChecked
。
如何在元素滚动时调用函数,但避免 Angular 的更改检测?
最佳答案
我建议你使用 ngZone.runOutsideAngular。
constructor (private zone : NgZone) {}
ngAfterViewInit () : any {
this.zone.runOutsideAngular(() => {
window.addEventListener('scroll', (e)=> {
console.log( 'scroll event fired' );
});
});
}
关于javascript - 如何防止滚动变化检测? ( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56339104/