Implement Infinite Scrolling Using Angular 6

In this article, we are going to learn that how to implement infinite scroll using angular 6.

Introduction
 
In this article, we are going to implement the infinite scroll in our Angular 6 app. When we are developing any application, at that time we deal with tons of records at a time. In this situation a question will be raised  --  how to show thousands of a records in a single page?
 
It's not a good practice to load thousands of records at the same time into a single page, and there are many advantages to implementing infinite scroll.
  • Boost our website's time so that we can have faster operations
  • Increase the page level depth in an easy manner
  • Minimum number of clicks required
  • Enhance the user interface
  • Better for the mobile layout 
  • One of the main advantages is that it decreases a website's bounce rate  
We are going to learn one of the ways to implement infinite scrolling without complex settings. Before starting with this article you can always clone the source code from Github here.
 
To implement the infinite scroll into Angular, I'm using an npm package called ngx-infinite-scroll which supports angular 6.0.0 as well. You can find more information about the ngx-infinite-scroll package in detail here.
 
To get started with infinite scroll, we just need to create a new project by following a few steps which are described below.
 
Create a new Angular project by following a few commands.
  1. ng new ng6infinitescroll  
When the project will be created, just go to that directory in which project was created and use npm command.
  1. npm install // to install dependencies  
  2.   
  3. ng serve // to run angular app  
Above are the basic required steps to create and execute the project, additionally we need to install another npm package called ngx-infinite-scroll to work with infinite scroll into our application, for that we just need to use the below npm command.
  1. npm install ngx-infinite-scroll --save  
Apart from the above dependencies, I have used angular material to design my page, for that i have installed angular/cdk.
  1. npm install @angular/cdk  
To implement infinite scroll, let's first design our user interface, for that open app.component.html and paste the below code.
  1. <mat-toolbar color="accent">  
  2.   <span>Manav Pandya - C#Corner</span>  
  3.   <span class="demo-toolbar"></span>  
  4. </mat-toolbar>  
  5.   
  6. <mat-card>  
  7.   <div class="container">  
  8.     <div class="row" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" (scrolled)="onScroll()" [scrollWindow]="false"  
  9.     style="height: 400px; overflow-y: scroll;">  
  10.       <div *ngFor="let item of myPhotosList" class="col-md-4" style="margin-top: 10px;">  
  11.         <img style="height: 220px;width: 315px;" src="{{item.url}}" />  
  12.       </div>  
  13.     </div>  
  14.   </div>  
  15. </mat-card>  
Here I have used the two material components to hold images data into card-component and a toolbar which contains the title of my single page application, additionally i have used division tag to hold list of images to render inside card-component.
 
For that i have provided few properties to an element to work with scrolling.
  • infiniteScroll
    It is the primary property that defines the content is being scrolled.
  • infiniteScrollDistance
    Used to provide distance where we will reach up to the defined percentage of the element, at that time scroll event will be triggered.
  • infiniteScrollThrottle
    Number of milliseconds after the scroll event will be triggered.
  • scrolled
    It is a method to perform a specific action when scroll is being reached.
  • scrollWindow
    We should decide that we want to listen to window scroll event or the element scroll event, here in this demo I have used false because I'm using element to be scrolled.
So these are some properties I have used in this demo project, but you can use more methods or properties as per your requirements. The next part is to use some dummy data to load into the element for scrolling, for that I'm going to use fake rest api data of jsonPlaceHolder.
 
To explain the exact mechanism of scrolling, we need a large amount of data so that we can see the actual result, to learn more about jsonplaceholder fake api just click here 
 
Create the service in angular project by using the below npm command, which generates a service file.
  1. ng generate service mydataservice  
When mydataservice.service.ts file will be created, I have modified my service code which looks like the given code snippet.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient , HttpHeaders  } from '@angular/common/http';  
  3.   
  4. @Injectable()  
  5. export class MydataserviceService {  
  6.   
  7.   constructor(private http: HttpClient) { }  
  8.   
  9.   // Method to call api to get images  
  10.   getMyPhotos(page: number)  
  11.   {  
  12.     return this.http.get('https://jsonplaceholder.typicode.com/photos?_page='+page);  
  13.   }  
  14. }  
So far we have created our user interface and service to call and get dummy data to load into our scroll window, now let's move to the component side to call and render layout with the fake data.
 
Open app.component.ts and paste the below code into it.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { MydataserviceService } from './mydataservice.service';  
  3. import { Photos, PhotosObj } from './_modal';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css'],  
  9.   providers: [MydataserviceService]  
  10. })  
  11. export class AppComponent implements OnInit {  
  12.   
  13.   title = 'app';  
  14.   myPhotosList: Photos[] = [];  
  15.   page: number = 1;  
  16.   
  17.   constructor(private service: MydataserviceService) { }  
  18.   
  19.   ngOnInit() {  
  20.     // To call api for initial image rendering  
  21.     this.getPhotos();  
  22.   }  
  23.   
  24.   // To get image data from api  
  25.   getPhotos() {  
  26.     console.log(this.page);  
  27.     this.service.getMyPhotos(this.page).subscribe((res) => this.onSuccess(res));  
  28.   }  
  29.   
  30.   // When we got data on a success  
  31.   onSuccess(res) {  
  32.     console.log(res);  
  33.     if (res != undefined) {  
  34.       res.forEach(item => {  
  35.         this.myPhotosList.push(new PhotosObj(item));  
  36.       });  
  37.     }  
  38.   }  
  39.   
  40.   // When scroll down the screen  
  41.   onScroll()  
  42.   {  
  43.     console.log("Scrolled");  
  44.     this.page = this.page + 1;  
  45.     this.getPhotos();  
  46.   }  
  47.   
  48. }  
As you can see in my component code I have created several methods, and the primary method is onScroll(). 
 
When we run our project, you can see the output like the below screen.
 
Implement Infinite Scrolling Using Angular 6
Initially on the first api call I'm getting 10 records, and then we can see the response of the rest api call.
 
Implement Infinite Scrolling Using Angular 6 
Total number of records in the api is around 5000, but we just have loaded 10 of them/ Now when I scroll down the element, the result of the api will be added to existing records, observe the second api call for the scroll event.
 
Implement Infinite Scrolling Using Angular 6 
In short I'm loading 10 records at a time to populate elements with newly added records. This enhances website performance, and it also leads users to load data as per the requirement.
 
When you complete this article, you will be able to get the output as per the below gif screen.
 
Implement Infinite Scrolling Using Angular 6
Conclusion
 
This is how we can implement a simple infinite scroll functionality using Angular 6.  To understand better, I suggest you get the source code from git repository here, or you can download the attached source code here with this article.
 
Thus this article does not follows standard coding, so it is advisable to use proper code standards. If you have any questions or suggestions then feel free to comment.  Thanks for reading.