Prevent a native browser event ( like scroll ) from firing change detection

白昼怎懂夜的黑 提交于 2019-11-28 20:48:19
yurzui

I can offer you several hacks to do that:

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

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

The corresponding plunkr is here http://plnkr.co/edit/NPHQqEmldC1z2BHFCh7C?p=preview

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

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

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

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' ); 
   });
});

The plunkr is here http://plnkr.co/edit/jXBlM4fONKSNc7LtjChE?p=preview

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

Update:

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' );
  } ); 
});

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!