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.
When the project will be created, just go to that directory in which project was created and use npm command.
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.
- 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.
To implement infinite scroll, let's first design our user interface, for that open app.component.html and paste the below code.
- <mat-toolbar color="accent">
- <span>Manav Pandya - C#Corner</span>
- <span class="demo-toolbar"></span>
- </mat-toolbar>
-
- <mat-card>
- <div class="container">
- <div class="row" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" (scrolled)="onScroll()" [scrollWindow]="false"
- style="height: 400px; overflow-y: scroll;">
- <div *ngFor="let item of myPhotosList" class="col-md-4" style="margin-top: 10px;">
- <img style="height: 220px;width: 315px;" src="{{item.url}}" />
- </div>
- </div>
- </div>
- </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.
- 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.
- import { Injectable } from '@angular/core';
- import { HttpClient , HttpHeaders } from '@angular/common/http';
-
- @Injectable()
- export class MydataserviceService {
-
- constructor(private http: HttpClient) { }
-
-
- getMyPhotos(page: number)
- {
- return this.http.get('https://jsonplaceholder.typicode.com/photos?_page='+page);
- }
- }
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.
- import { Component, OnInit } from '@angular/core';
- import { MydataserviceService } from './mydataservice.service';
- import { Photos, PhotosObj } from './_modal';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css'],
- providers: [MydataserviceService]
- })
- export class AppComponent implements OnInit {
-
- title = 'app';
- myPhotosList: Photos[] = [];
- page: number = 1;
-
- constructor(private service: MydataserviceService) { }
-
- ngOnInit() {
-
- this.getPhotos();
- }
-
-
- getPhotos() {
- console.log(this.page);
- this.service.getMyPhotos(this.page).subscribe((res) => this.onSuccess(res));
- }
-
-
- onSuccess(res) {
- console.log(res);
- if (res != undefined) {
- res.forEach(item => {
- this.myPhotosList.push(new PhotosObj(item));
- });
- }
- }
-
-
- onScroll()
- {
- console.log("Scrolled");
- this.page = this.page + 1;
- this.getPhotos();
- }
-
- }
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.
Initially on the first api call I'm getting 10 records, and then we can see the response of the rest api call.
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.
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.
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.