Infinite Scroll In Angular 7 Using Web API And SQL Server

The back-end used here is a SQL Server database. We notice on many websites like Facebook, that when we log into the website and click on the Notifications button, then it initially loads only a few notifications whereas after we scroll down, it dynamically loads a whole lot of notifications. So, we will work on the same type of scenario here. First, let us understand the "Infinite Scroll".

An infinite-scroll-list is a list where the data is being loaded asynchronously when the user scrolls further down the application. It’s a great way to avoid a pager (where the user had to click on every time) and it can really keep the application's high performance.

Now, we will see with an example. In that example, when we run the project the first time, it will load only 5 records and when we draw the scroll, then it will load the next records. In that example, all records will come from the database with API so let us create a database and table, an API, and an Angular application step by step.

Step 1. Create a database table

Infinite Scroll In Angular 7 Using Web API And SQL Server

You can download the table and record script files from the attachment at the top of this article.

Note
If you already have an existing database and table, you can skip this step.

Step 2. Create a Web API Project

Now, we will create a Web API with the functionality of binding records from the database. Go to Visual Studio >> File >> New >> Project >> Web Application. After that, click OK and you will see the templates. Select the Web API template.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Click OK.

Step 3. Add ADO.NET Entity Data Model

Now, select the Models folder. Right-click on Add >> New Item. Select Data in the left panel and choose ADO.NET Entity Data Model.

Infinite Scroll In Angular 7 Using Web API And SQL Server
 
Infinite Scroll In Angular 7 Using Web API And SQL Server 

Now, click the "Add" button and select EF Designer from the database and click Next. After that, give your SQL credentials and select the database where you have your database table and data.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Click the "Add" button and select your table and click on the "Finish" button.

Step 4. Bind Records

Now, we will write the code to perform the binding operation.

Go to the Controllers folder in your API application and right-click to go to Add >> Controller >> Select Web API 2 Controller-Empty.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Now, we will go to the controller class and set the routing to make it more user-friendly by writing the below code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.Web.Http;  
  6. using BindRecordsAPI.Models;  
  7.   
  8. namespace BindRecordsAPI.Controllers  
  9. {  
  10.     [RoutePrefix("Api/AngularAPI")]  
  11.     public class UserController : ApiController  
  12.     {  
  13.         [HttpGet]  
  14.         [Route("AllUserDetails")]  
  15.         public Task<IEnumerable<UserDetail>> AllUser(int pageNumber)  
  16.         {  
  17.             IEnumerable<UserDetail> lstUser = new List<UserDetail>();  
  18.             pageNumber = pageNumber * 10;  
  19.             try  
  20.             {  
  21.                 using (AngularDBEntities objEntity = new AngularDBEntities())  
  22.                 {  
  23.   
  24.                     lstUser = objEntity.UserDetails.Take(pageNumber).ToList();  
  25.                 }  
  26.   
  27.             }  
  28.             catch (Exception)  
  29.             {  
  30.                 throw;  
  31.             }  
  32.   
  33.             return Task.Run(() => lstUser);  
  34.   
  35.         }  
  36.     }  
  37. }  

As you may see from the above code, it has functionality BindRecordsApi to the table.

Step 5. Build UI Application

Now, we will create the Web application in Angular 7 that will consume the Web API.

First, we have to make sure that we have Angular CLI installed.

Open the command prompt, and type the below code followed by a hit on ENTER.

npm install -g @angular/cli

Now, open the Visual Studio Code editor and create a project.

Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. We name it InfiniteScroll.

ng new InfiniteScroll

After that, hit ENTER. It will take a while to create the project.

Once created, the project should look like this.

Now, we will create components to provide UI.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

I'm going to create a new component, User.

Go to the TERMINAL and go to your Angular project location using the following command.

cd projectName

Now, write the following command that will create a component.

ng g c user

Press ENTER.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Note
You can see that the component is created.

Step 6. Create a Class

Now, let us create an interface like a model class.

Open TERMINAL and write the below command:

ng g class model/user --spec=false

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Now, write all properties of the User class related to a user that matches with the database.

  1. export class User {  
  2.     UserId: number;  
  3.     UserName: string;  
  4.     EmailId: string;  
  5.     Gender: string;  
  6.     Address: string;  
  7.     MobileNo: string;  
  8.     PinCode: string;  
  9. }  

Step 7. Create Service

Now, we will create a service.

Open the TERMINAL and write the below command.

ng g s service/user --spec=false

Press ENTER and you will see the service files.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Now, open user.service.ts, import necessary classes and libraries, and then make calls to the WebAPI methods.

  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';    
  3. import { User } from '../model/user';  
  4. import { Observable } from 'rxjs';  
  5.   
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class UserService {
    url = "http://localhost:63278/";
    constructor(private http: HttpClient) { }
    UserDetails(page : number): Observable<User[]> {
    return this.http.get<User[]>(this.url + 'Api/AngularAPI/AllUserDetails?pageNumber=' + page);
    }
    }

Step 8. Install and Configure Angular Material Theme

We will use an Angular Material theme to create a rich, interactive, and device-oriented UI for our Web app.

Let's install the Angular Material theme.

Open TERMINAL again and write the below command.

npm install --save @angular/material @angular/cdk @angular/animations

If you want to learn more about Angular Material, visit here: link.

After it's installed successfully, we can check in the package.json file.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Before the use of Angular Material, we need to add the necessary library. Here, we will create a separate module for adding the library.

Open TERMINAL again and write the below command.

ng generate module material/angularmaterial --spec=false

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Now, open angularmaterial.module.ts and first import the necessary class and libraries and then make calls to the WebAPI methods.

  1. import {A11yModule} from '@angular/cdk/a11y';    
  2. import {DragDropModule} from '@angular/cdk/drag-drop';    
  3. import {PortalModule} from '@angular/cdk/portal';    
  4. import {ScrollingModule} from '@angular/cdk/scrolling';    
  5. import {CdkStepperModule} from '@angular/cdk/stepper';    
  6. import {CdkTableModule} from '@angular/cdk/table';    
  7. import {CdkTreeModule} from '@angular/cdk/tree';    
  8. import {NgModule} from '@angular/core';    
  9. import {    
  10.    
  11.   MatCardModule,    
  12.   MatIconModule,    
  13.   MatInputModule,    
  14.   MatListModule,    
  15.   MatMenuModule,    
  16.   MatPaginatorModule,    
  17.   MatProgressBarModule,    
  18.   MatSortModule,    
  19.   MatStepperModule,    
  20.   MatTableModule,    
  21.   MatTabsModule,    
  22.   MatToolbarModule  
  23. } from '@angular/material';    
  24.     
  25. @NgModule({    
  26.   exports: [    
  27.     A11yModule,    
  28.     CdkStepperModule,    
  29.     CdkTableModule,    
  30.     CdkTreeModule,    
  31.     DragDropModule,    
  32.     MatCardModule,    
  33.   MatIconModule,    
  34.   MatInputModule,    
  35.   MatListModule,    
  36.   MatMenuModule,    
  37.   MatPaginatorModule,    
  38.   MatProgressBarModule,    
  39.   MatSortModule,    
  40.   MatStepperModule,    
  41.   MatTableModule,    
  42.   MatTabsModule,    
  43.   MatToolbarModule,   
  44.     PortalModule,    
  45.     ScrollingModule,    
  46.   ]    
  47. })    
  48. export class AngularmaterialModule { }    

Step 9. ngx-infinite-scroll

We have completed the required steps to create and execute the project, and 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, we have used Angular material to design our page, and for that we will install angular/cdk.

npm install @angular/cdk 

Now we will write code for perform scrolling in the ts file, but before that we need to understand some properties and events that we will use our application.

Properties

InfiniteScroll: It is the primary property that defines the content being scrolled

InfiniteScrollDistance: The bottom percentage point of the scroll nob relative to the infinite-scroll is an event which if triggered, will fire the scrolled event.

InfiniteScrollThrottle: Should get a number of milliseconds for throttle. The event will be triggered this many milliseconds after the user stops scrolling.

Events

Scrolled: This will callback if the distance threshold has been reached on a scroll down.

For more details click here.

Step 10. Implement component class

Now we will write code for performing the bind records and loading functionality. In the demo we will load the first 10 records. Open user.component.ts file and write the below code.

  1. import { Component, OnInit } from '@angular/core';  
  2. import { User } from '../model/user';  
  3. import { UserService } from '../service/user.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-user',  
  7.   templateUrl: './user.component.html',  
  8.   styleUrls: ['./user.component.css']  
  9. })  
  10. export class UserComponent implements OnInit {  
  11.   allUser: User[] = [];  
  12.   page: number = 1;  
  13.   constructor(private service: UserService) { }  
  14.   displayedColumns: string[] = ['UserId''UserName''EmailId''Gender''Address''MobileNo''PinCode'];  
  15.   ngOnInit() {  
  16.     this.AllUserDetails();  
  17.   }  
  18.   
  19.   AllUserDetails() {  
  20.     this.service.UserDetails(this.page).subscribe((res) => {  
  21.       this.allUser = res;  
  22.     });  
  23.   }  
  24.   onScroll() {  
  25.     this.page = this.page + 1;  
  26.     this.AllUserDetails();  
  27.   }  
  28. }  

Open user.component.html file and write the below code.

  1. <mat-toolbar color="accent" layout-align-md="center end">  
  2.   <span class="demo-toolbar">infinite Scroll Example</span>  
  3. </mat-toolbar>  
  4. <mat-card>  
  5.   <div class="container">  
  6.     <div class="row" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" (scrolled)="onScroll()"  
  7.       [scrollWindow]="false" style="height: 400px; overflow-y: scroll;">  
  8.   
  9.       <table mat-table [dataSource]="allUser">  
  10.         <ng-container matColumnDef="FirstName">  
  11.           <th mat-header-cell *matHeaderCellDef> FirstName </th>  
  12.           <td mat-cell *matCellDef="let element"> {{element.FirstName}} </td>  
  13.         </ng-container>  
  14.          
  15.         <ng-container matColumnDef="LastName">  
  16.           <th mat-header-cell *matHeaderCellDef> LastName </th>  
  17.           <td mat-cell *matCellDef="let element"> {{element.LastName}} </td>  
  18.         </ng-container>  
  19.         
  20.         <ng-container matColumnDef="UserId">  
  21.           <th mat-header-cell *matHeaderCellDef> UserId </th>  
  22.           <td mat-cell *matCellDef="let element"> {{element.UserId}} </td>  
  23.         </ng-container>  
  24.          
  25.         <ng-container matColumnDef="UserName">  
  26.           <th mat-header-cell *matHeaderCellDef> UserName </th>  
  27.           <td mat-cell *matCellDef="let element"> {{element.UserName}} </td>  
  28.         </ng-container>  
  29.           
  30.         <ng-container matColumnDef="EmailId">  
  31.           <th mat-header-cell *matHeaderCellDef> EmailId </th>  
  32.           <td mat-cell *matCellDef="let element"> {{element.EmailId}} </td>  
  33.         </ng-container>  
  34.          
  35.         <ng-container matColumnDef="Gender">  
  36.           <th mat-header-cell *matHeaderCellDef> Gender </th>  
  37.           <td mat-cell *matCellDef="let element"> {{element.Gender ==0? 'Male' : 'Female'}} </td>  
  38.         </ng-container>  
  39.          
  40.         <ng-container matColumnDef="Address">  
  41.           <th mat-header-cell *matHeaderCellDef> Address </th>  
  42.           <td mat-cell *matCellDef="let element"> {{element.Address}} </td>  
  43.         </ng-container>  
  44.         <ng-container matColumnDef="MobileNo">  
  45.           <th mat-header-cell *matHeaderCellDef> MobileNo </th>  
  46.           <td mat-cell *matCellDef="let element"> {{element.MobileNo}} </td>  
  47.         </ng-container>  
  48.         <ng-container matColumnDef="PinCode">  
  49.           <th mat-header-cell *matHeaderCellDef> PinCode </th>  
  50.           <td mat-cell *matCellDef="let element"> {{element.PinCode}} </td>  
  51.         </ng-container>  
  52.         <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>    
  53.         <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>    
  54. </table>   

Open user.component.css file and write the below code.

  1. th{  
  2.     background-color: #428BCA;  
  3.     color: white;  
  4.     width:200px;  
  5.     font-size: large;  
  6. }  

Open app.component.html file and write the below code.

  1. <div class="container">  
  2.    <app-user></app-user>  
  3. </div>  

 Step 11. Setting CORS

Now that we have completed all code functionality we will run the project but before that we have to set the CORS, because if you consume the Web API, Angular blocks the URL and we called this issue CORS (Cross OriginResource Sharing).

First, let's resolve this problem.

Go to the Web API project.

Download a Nuget package for CORS. Go to NuGet Package Manager and download the following file.

After that, go to App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Add namespace

  1. using System.Web.Http.Cors;  

After that add the below code inside the Register method,

  1. var cors = new EnableCorsAttribute("*""*""*"); //origins,headers,methods    
  2.           config.EnableCors(cors);   

Step 12. Run

We have completed all needed code functionality for our functionality. Before running the application, first make sure to save your work.

Now, let's run the app and see how it works. 

Open TERMINAL and write the following command to run the program.

ng serve -o

The output looks like the following image. It's a stunning UI that's been created.

Infinite Scroll In Angular 7 Using Web API And SQL Server 

Let's check full functionality,

Infinite Scroll In Angular 7 Using Web API And SQL Server 

We've finished performing bind records and loading records. The app uses a Web API to provide data access from the SQL Server. 

Thank you for reading my article.


Similar Articles