Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 369
Sagi Avatar asked Dec 28 '15 15:12

Sagi


People also ask

How do you do infinite scroll in ionic 4?

You can access the infinite scroll by using the standard <ion-infinite-scroll> and <ion-infinite-scroll-content> component. The expression (ionInfinite) = "loadData($event)" assigned in the <ion-infinite-scroll> is called when the user reaches close to the defined distance.

How infinite scroll is implemented in AngularJS?

ngInfiniteScroll is a directive that you can use to implement infinite scrolling in your AngularJS applications. Simply declare which function to call when the user gets close to the bottom of the content with the directive and the module will take care of the rest.

How do you use continuous scrolling?

Continuous Scrolling Scroll continuously through the pages of your document instead of paging through one or two at a time. This is also a default mode. Turn this off or on by choosing View > Continuous, or by clicking on the Sidebar menu item. This setting persists across newly opened documents.


2 Answers

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);
  }
}
like image 174
alexpods Avatar answered Sep 21 '22 08:09

alexpods


You can use @HostListener to detect Scrolling. This is how I have done this

 export class AppComponent {

  @HostListener('window:scroll', ['$event'])
    onScroll($event: Event): void {
    console.log("On Scroll");
    //Logic To Check whether we are bottom of the page
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
      console.log("On Scroll Down");
      //Write logic here for loading new content.
    }
  }

}

Hope this will help you :)

like image 24
Ashish Sharma Avatar answered Sep 19 '22 08:09

Ashish Sharma