Sagi Sagi - 1 month ago 34
TypeScript Question

implement infinite scroller in angular2

I would like to implement infinite scrolling for an *ng-for of DIVs in angular2 component. For this I need to somehow hook to the window onScroll event via angular method. Then in angular I will be able to load more items into the data items array when user has scrolled pass some point of the page.

Anyone has ideas how to hook to the window.scroll event from angular (inside ng2 component)?

Answer

Use (target:event)="handler()" notation for listening to global events. You can use window, document or body as a target. For your case it will be (window:scroll)="onScroll($event)". See this plunk.

import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  template: `
    <div (window:scroll)="onScroll($event)">
      <h1>Hello Angular2</h1>
      ...
    </div>
  `,
})
export class App {

  onScroll(event) {
    console.log('scroll event', event);
  }
}