Implementation Of Ngx Infinite Scroller Using Angular Application

Introduction

 
In this article, we will integrate an infinite scroller. In this example when we scroll down, only a few items will show on the screen. After scrolling to the bottom, it will load the next data and it will be attached to the screen. To implement this, we need to install the Ngx-infinite scroller package from the node package manager.
 
For this example I am using the Google Pixel photo search API, which I have already implemented the search example which I am using in this example just to show how infinite scroller works, you can find its link here.
 
Prerequisites
  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed

Create an Angular project

 
Step 1
 
Create a new Angular project using the following NPM command:
 
ng new infiniteScrollerExample
 
Step 2
 
Open the newly-created project in Visual Studio code and install ngx-infinite-scroll using the below command:
 
npm install ngx-infinite-scroll
 
Step 3
 
Now, let's create a new component, by using the following command.
 
ng g c infinite-scroller
 
Step 4
 
Now open infinite-scroller.component.html file and add the following code:
  1. <h1 align='center' >Infinite scroller Example</h1>    
  2. <div class="search-results"    
  3.       infinite-scroll    
  4.       [infiniteScrollDistance]="scrollDistance"    
  5.       [infiniteScrollUpDistance]="scrollUpDistance"    
  6.       [infiniteScrollThrottle]="throttle"    
  7.       (scrolled)="onScrollDown()">    
  8.       <div class="container">    
  9.         <div class="row">    
  10.           <div *ngFor="let pic of array;let i=index" class="col-sm-4">    
  11.             <div style="margin-top: 10px;" class="card">    
  12.               <img class="card-img-top" [src]="pic.src.landscape" alt="Card image cap">    
  13.               <div class="card-body">    
  14.                 <h5 class="card-title">{{i+1}}</h5>    
  15.                 <a href="#" class="btn btn-primary">Know more</a>    
  16.               </div>    
  17.             </div>    
  18.           </div>    
  19.         </div>    
  20.       </div>    
  21. </div>    
 
Step 6
 
The next step is to open infinite-scroller.component.ts file and add the following code:
  1. import { Component, OnInit } from '@angular/core';  
  2. import { PexelPhotoSearchService } from '../pexel-photo-search.service';  
  3.   
  4.   
  5. @Component({  
  6.   selector: 'app-infinite-scroller',  
  7.   templateUrl: './infinite-scroller.component.html',  
  8.   styleUrls: ['./infinite-scroller.component.css']  
  9. })  
  10. export class InfiniteScrollerComponent implements OnInit {  
  11.   array = [];  
  12.   sum = 10;  
  13.   throttle = 300;  
  14.   scrollDistance = 1;  
  15.   scrollUpDistance = 2;  
  16.   direction = "";  
  17.   modalOpen = false;  
  18.   photos: any;  
  19.   start: number = 0;  
  20.   
  21.   constructor(private pexelPhotoSearchService: PexelPhotoSearchService) {  
  22.   }  
  23.   
  24.   ngOnInit() {  
  25.     this.getPhoto();  
  26.   }  
  27.   getPhoto() {  
  28.     this.pexelPhotoSearchService.getdata('bikes'this.sum).subscribe((response: any) => {   
  29.       this.photos = response.photos;  
  30.       this.addItems(this.start, this.sum);  
  31.     }, (error) => {  
  32.       console.log(error);  
  33.     })  
  34.   }  
  35.   
  36.   selector: string = '.main-panel';  
  37.   
  38.   addItems(index, sum) {  
  39.     for (let i = index; i < sum; ++i) {  
  40.       debugger  
  41.       this.array.push(this.photos[i]);  
  42.       console.log(this.array);  
  43.   
  44.     }  
  45.   }  
  46.   
  47.   onScrollDown(ev) {  
  48.   
  49.     // add another 20 items  
  50.     this.start = this.sum;  
  51.     this.sum += 20;  
  52.     this.getPhoto();  
  53.     this.direction = "down";  
  54.   }  

  55. }  
 
In the above image of the scroll down method, first, it will show only 20 records. After we scroll down, it will add 20 records in the sum variable, and the start variable will be the sum.
 
Step 7
 
Here, we need to add one file inside assets folder which includes the coordinates of our polygon to mark it using latitude and longitude inside Google Maps.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';  
  3. import { Observable,throwError } from 'rxjs';  
  4. import {catchError} from 'rxjs/operators';  
  5.   
  6. const httpOptions={  
  7.   headers : new HttpHeaders({  
  8.     'Authorization':'563492ad6f917000010000014060d806c66c47b88b9b4d7f8c487692'  
  9.   })  
  10. }  
  11.   
  12. @Injectable({  
  13.   providedIn: 'root'  
  14. })  
  15. export class PexelPhotoSearchService {  
  16.    
  17.   constructor(private http:HttpClient) { }  
  18.   
  19.   getdata(search,perPage):Observable<any>{  
  20.     const url="https://api.pexels.com/v1/search?query="+search+"&per_page="+perPage;  
  21.     return this.http.get<any>(url,httpOptions).pipe(catchError(this.handelError));  
  22.   }  
  23.   handelError(error){  
  24.     return throwError(error.message || "Server Error");  
  25.   }  
  26. }  
 
Step 8
 
Here, we need to add one file inside assets folder which includes the coordinates of our polygon to mark it using latitude and longitude inside Google Maps.
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from '@angular/forms';  
  4.   
  5. import { AppComponent } from './app.component';  
  6. import { InfiniteScrollModule } from 'ngx-infinite-scroll';  
  7. import { InfiniteScrollerComponent } from './infinite-scroller/infinite-scroller.component';  
  8. import { HttpClientModule } from '@angular/common/http';  
  9. import { OnlyNumberComponent } from './only-number/only-number.component';  
  10. declare const chance;  
  11.   
  12. @NgModule({  
  13.   imports: [BrowserModule, FormsModule, InfiniteScrollModule, HttpClientModule],  
  14.   declarations: [AppComponent, InfiniteScrollerComponent, OnlyNumberComponent],  
  15.   bootstrap: [AppComponent]  
  16. })  
  17. export class AppModule { }  
 
Output
 

Conclusion 

 
In this article, we learned how to create an infinite scroller that will boost and improve our application performance.
 
I hope you have enjoyed this article as much as I have enjoyed writing and coding the examples.
 
Please let me know how to improve it.