Angular 12 Infinite Scroll Example – Auto Load Data on Reaching Bottom

Adding Infinite scroll component in Angular application for example; In this Angular tutorial, we will learn how to add infinitely scroll content in Angular application. Infinite means, the data will keep on loading when a user reaches the bottom of the content.

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12

Infinite means, without any limit; In some situations, we have huge data to show on the user screens. But we can’t load the whole data at once and dump it onto the screen to render. In such a case, it will take loads of time to load, even if it is loaded it will be unmanageable for limited resources for browsers to render.

Using the infinite strategy, we can load data in chunks from the server to the user screen. In this way, when a user reads previous data and scrolls downs we load some more data and fed it to the scrollable container. Thus, infinite features make applications more efficient, user-friendly, data-saver as we are not fetching not required data at once.

In this tutorial, we will discuss how to easily and quickly implement the infinite scrollable component by using a profound package named npx-infinite-scroll. Moreover, we will check all important properties and event configurations to make it more flexible for your app.

How to Add Infinite Scrollbar in Angular application?

  1. Create Angular Application
  2. Add Bootstrap Style
  3. Install Npx-Infinite-Scroll Package
  4. Update App Module
  5. Adding Infinite Scroll Component (Track Window Scrollbar)
  6. Add Infinite Scroll to Any Container
  7. Properties and Event Handlers
  8. Serve Angular Application

 

Create Angular Application

Before creating the Angular application, make sure you have Angular CLI installed on your system.

$ npm install -g @angular/cli

After that, you are ready to create a new Angular project. Execute below CLI command to create a new angular application.

$ ng new angular-infinite-scroll-app

Move into the project directory

$ cd angular-infinite-scroll-app

Add Bootstrap Style

To quickly style our application, head towards the index.html file at application root, and include the bootstrap.min.css file in the head section.
<head>
   ....
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

Install Npx-Infinite-Scroll Package

Next, install the Infinite Scroll package in your application. Execute below npm command to install the ngx-infinite-scroll package.

$ npm install ngx-infinite-scroll --save

 

Update App Module

After installing the package, we need to configure the App Module to import the required modules. So that the Infinite Scroll component directive are available acroose the application.

Open the app.module.ts file and import the InfiniteScrollModule and update the imports array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { InfiniteScrollModule } from 'ngx-infinite-scroll';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    InfiniteScrollModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Adding Infinite Scroll Component( Track Window Scrollbar)

Now, we will add out Infinite Scroll component in the App Component. An infinite scrollable container can be created by adding the infinite-scroll directive with few other properties and event handlers.

<div class="search-results" 
    infinite-scroll 
    (scrolled)="onScrollDown($event)" 
    (scrolledUp)="onScrollUp($event)">

      <div class="list-group">
        <a class="list-group-item list-group-item-action" *ngFor="let i of listArray">
          <p class="mb-1">{{i}} Item added on {{direction}}</p>
        </a>
      </div>

</div>

Above, we have a div container with a class, other then that the infinite-scroll directive property is important to make it actually infinite scrollable element.

The (scrolled) and (scrolledUp) event handlers are used to track scroll direction up or down respectively. Using these events we’ll be loading more items to append or prepend to our listArray.

By default windows scrollbar will be considered to track scroll events. We can bind scroll event to self-contained element with its own scrollbar. That we will discuss in next section.

In the app.component.ts class file update the following code.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  listArray : string[] = [];
  sum = 20;
  direction = "";

  constructor() {
    this.appendItems();
  }


  onScrollDown(ev: any) {
    console.log("scrolled down!!", ev);

    this.sum += 20;
    this.appendItems();
    
    this.direction = "scroll down";
  }

  onScrollUp(ev: any) {
    console.log("scrolled up!", ev);
    this.sum += 20;
    this.prependItems();

    this.direction = "scroll up";
  }

  appendItems() {
    this.addItems("push");
  }

  prependItems() {
    this.addItems("unshift");
  }

  addItems(_method: string) {
    for (let i = 0; i < this.sum; ++i) {
      if( _method === 'push'){
        this.listArray.push([i].join(""));
      }else if( _method === 'unshift'){
        this.listArray.unshift([i].join(""));
      }
    }
  }
}

We are adding up 20 items using the "push" or "unshift" JavaScript methods to append or prepend items based on Scroll Up or Scroll Down event is triggered.

The appendItem() method is getting called at the beginning to load first set of items by default. Other then that, we don’t have much here, implementation is very simple. In real scenerieos you may have HTTP call to get records remotely. That stuff will go inside the addItems() method.

Add Infinite Scroll to Any Container

Now, lets discuss how to add infinite scroller on any container having its own scrollbar. For that we need to set [scrollWindow]="false" to the container as shown below.

<div class="search-results-container" 
    infinite-scroll  
    [scrollWindow]="false"
    (scrolled)="onScrollDown($event)" 
    (scrolledUp)="onScrollUp($event)">

      <div class="list-group">
        <a class="list-group-item list-group-item-action" *ngFor="let i of listArray">
          <p class="mb-1">{{i}} Item added on {{direction}}</p>
        </a>
      </div>

</div>

The serch-results-container class will have following style, with its own height and width defined. Add this style in the app.component.scss file.

.search-results-container{
    margin: 40px;
    height: 350px;
    width: 500px;
    overflow: auto;
}

Else will remain same, the [scrollWindow] will its magic to implement infinite scrollable feature to any container. Let’s have a look on important properties and methods provided by Infinite Scroll package.

Properties and Event Handlers

There are number of properties and methods to configure the behaviour of infinite scroll as per needs. Lets have  a look in more details.

@Input() Properties:

  • infiniteScrollDistance : number; options; default = 2 – Bottom percentage point of the scroll nob relatively to the infinite-scroll container (i.e, 2 (2 * 10 = 20%) is event is triggered when 80% (100% – 20%) has been scrolled).
  • infiniteScrollUpDistance : number; optional;1.5 – Similer to infiniteScrollDistance but in Up direction.
  • infiniteScrollThrottle : number; optional;150 – The event will be triggered this many milliseconds after the user stops scrolling.
  • scrollWindow : boolean; optional; true – Listens to the window scroll instead of the actual element scroll. You can set to false, to listen to container’s own scroll.
  • immediateCheck : boolean; optional; false – Invokes the handler immediately to check if a scroll event has been already triggred when the page has been loaded (i.e. – when you refresh a page that has been scrolled)
  • infiniteScrollDisabled : boolean; optional; false – Doesn’t invoke the handler if set to true.
  • horizontal : boolean; optional; false – Sets the scroll to listen for horizontal events
  • alwaysCallback: boolean; optional; false – Instructs the scroller to always trigger events.
  • infiniteScrollContainer : string / HTMLElement; optional; null – Should get a html element or css selector for a scrollable element; window or current element will be used if this attribute is empty.
  • fromRoot : boolean; optional; false – If infiniteScrollContainer is set, this instructs the scroller to query the container selector from the root of the document object.

 

@Output() Methods/ Event handlers:

  • scrolled : This will callback if the distance threshold has been reached on a scroll down.
  • scrolledUp : This will callback if the distance threshold has been reached on a scroll up.

 

Serve Angular Application

Now, you can see the infinite scroll bar implementation in action, run the Angular application by hitting below npm command.

$ npm serve –open

This will open the application on default 4200 port on following URL.

http://localhost:4200

 

Conclusion

The ngx-infinite-scroll package is very popular and used by many elite brands. This package is very flexible to configure with number of controllable properties and methods. We discussed how to implement infinite scrollbar feature in Angular application very quickly.

Do share you thoughts and feedbacks, thanks…

 

Leave a Reply

Your email address will not be published. Required fields are marked *