Angular 2 equivalent to window.onscroll()?

14,626 views
Skip to first unread message

Vern Jensen

unread,
May 13, 2016, 12:31:04 AM5/13/16
to AngularJS
I have an angular directive I'd like to 'listen' to an onscroll() event. But window.onscroll() can have only one listener. Is there an Angular2 event I can register for instead, so each directive gets this event?

Sander Elias

unread,
May 13, 2016, 1:37:22 AM5/13/16
to AngularJS
Hi Vern,

You can attach as many scroll events as you like. See this example if you don't believe me:

<!DOCTYPE html>
<html lang="en">
 
<head>
 
<meta charset="UTF-8" />
 
<style>
 
#container {
    position
: absolute;
    height
: auto;
    top
: 0;
    bottom
: 0;
    width
: auto;
    left
: 0;
    right
: 0;
    overflow
: auto;
 
}
 
#foo {
    height
:1000px;
    width
:1000px;
    background
-color: #777;
    display
: block;
 
}
 
</style>
 
</head>
 
<body>
   
<div id="container">
     
<div id="foo"></div>
   
</div>
   
<script type="text/javascript">

     
var container = document.getElementById('container')
      container
.addEventListener('scroll', () => console.log('ev1'))
      container
.addEventListener('scroll', () => console.log('ev2'))
      container
.addEventListener('scroll', () => console.log('ev3'))

   
</script>
 
</body>
</html>

Of course there are performance penalties if you add to much processing on the scroll handler. You should at least debounce it. 
As you are using NG2, you can easily bind to this event by using something like this:

<div (scroll)='myScrollHandler'></div>

Does this help you a bit?

Regards
Sander

Guilherme Meireles

unread,
May 13, 2016, 7:37:06 AM5/13/16
to AngularJS
Hi Vern,

You can use the renderer to listen for the scroll event in the window.

constructor(private renderer: Renderer) {
    this.renderer.listenGlobal('window', 'scroll', (evt) => { console.log('scroll'); });
}

Regards,
Guilherme

Vern Jensen

unread,
May 13, 2016, 4:39:05 PM5/13/16
to AngularJS
Thanks Sander!!

I had already tried <div (scroll)="myFunction($event)", which I never got to work. Using container.addEventListener('scroll'...) didn't work for me either. BUT using window.addEventListener() DID. Thanks!

Guilherme -- is there any advantage to doing it through renderer versus window.addEventListener? (And window.removeEventListener in ngOnDestroy() )

Guilherme Meireles

unread,
May 13, 2016, 5:01:37 PM5/13/16
to AngularJS
Hi Vern,

One advantage is that the code gets decoupled from the DOM so it is easier to test.
I am not sure about this next part but maybe using the renderer your application would be able to take advantage of things like Angular Native and Angular in a webworker.

Regards,
Guilherme
Reply all
Reply to author
Forward
0 new messages