且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止本机浏览器事件(例如scroll)触发更改检测

更新时间:2022-06-16 21:58:23

我可以为您提供一些技巧:

I can offer you several hacks to do that:

1)只需将组件的检测策略设置为OnPush:

1) Just set detection strategy to OnPush on your component:

@Component({
  ...
  changeDetection: ChangeDetectionStrategy.OnPush
})

相应的插件在这里 http://plnkr.co/edit/NPHQqEmldC1z2BHFCh7C?p=预览

2)将zone.runOutsideAngular与本机window.addEventListener一起使用:

2) Use zone.runOutsideAngular together with the native window.addEventListener:

this.zone.runOutsideAngular(() => {
  window.addEventListener('scroll', (e)=> {
    console.log( 'scrolling' );
  });
});

另请参阅plunkr http://plnkr.co/edit/6Db1AIsTEGAirP1xM4Fy

See also plunkr http://plnkr.co/edit/6Db1AIsTEGAirP1xM4Fy

3)结合使用zone.runOutsideAngular和

3) Use zone.runOutsideAngular together with new instance of EventManager like this:

import { DomEventsPlugin, EventManager } from '@angular/platform-browser';
...
this.zone.runOutsideAngular(() => {
   const manager = new EventManager([new DomEventsPlugin()], new NgZone({enableLongStackTrace: false}));
   manager.addGlobalEventListener('window','scroll', (e) => {
     console.log( 'scrolling' ); 
   });
});

在此处插入代码 http://plnkr.co/edit/jXBlM4fONKSNc7LtjChE?p=preview

我不确定这是正确的方法.也许它可以帮助您前进...:)

I'm not sure that this is the right approach. Maybe it helps you in advancing... :)

更新:

此问题的答案:在Angular2的更改中视图未更新给了我第三种解决方案的想法. 第二个解决方案是有效的,因为窗口是在角度区域之外创建的.您不能只做:

Answer on this question: View is not updated on change in Angular2 gave me an idea for the third solution. Second solution is working because window was created outside of the angular zone. You can't do just:

this.zone.runOutsideAngular(() => {
  this.renderer.listenGlobal( 'window' , 'scroll' , ()=> {
      console.log( 'scrolling' );
  } ); 
});

它将不起作用,因为this.renderer是在角度区域内创建的. http://plnkr.co/edit/UKjPUxp5XUheooKuKofX?p=preview

It won't work because this.renderer was created inside angular zone. http://plnkr.co/edit/UKjPUxp5XUheooKuKofX?p=preview

我不知道如何创建新实例Renderer(在我们的案例中为DomRenderer),所以我只是在工作区域之外使用新实例NgZone创建了新实例EventManager.

I dont't know how to create a new instance Renderer(DomRenderer in our case) so i just created new instance EventManager outside of working zone and with new instance NgZone.