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
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.
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.
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.
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.
Now, we will go to the controller class and set the routing to make it more user-friendly by writing the below code.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web.Http;
- using BindRecordsAPI.Models;
-
- namespace BindRecordsAPI.Controllers
- {
- [RoutePrefix("Api/AngularAPI")]
- public class UserController : ApiController
- {
- [HttpGet]
- [Route("AllUserDetails")]
- public Task<IEnumerable<UserDetail>> AllUser(int pageNumber)
- {
- IEnumerable<UserDetail> lstUser = new List<UserDetail>();
- pageNumber = pageNumber * 10;
- try
- {
- using (AngularDBEntities objEntity = new AngularDBEntities())
- {
-
- lstUser = objEntity.UserDetails.Take(pageNumber).ToList();
- }
-
- }
- catch (Exception)
- {
- throw;
- }
-
- return Task.Run(() => lstUser);
-
- }
- }
- }
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.
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.
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
Now, write all properties of the User class related to a user that matches with the database.
- export class User {
- UserId: number;
- UserName: string;
- EmailId: string;
- Gender: string;
- Address: string;
- MobileNo: string;
- PinCode: string;
- }
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.
Now, open user.service.ts, import necessary classes and libraries, and then make calls to the WebAPI methods.
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { User } from '../model/user';
- import { Observable } from 'rxjs';
-
- @Injectable({
- providedIn: 'root'
- })
-
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.
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
Now, open angularmaterial.module.ts and first import the necessary class and libraries and then make calls to the WebAPI methods.
- import {A11yModule} from '@angular/cdk/a11y';
- import {DragDropModule} from '@angular/cdk/drag-drop';
- import {PortalModule} from '@angular/cdk/portal';
- import {ScrollingModule} from '@angular/cdk/scrolling';
- import {CdkStepperModule} from '@angular/cdk/stepper';
- import {CdkTableModule} from '@angular/cdk/table';
- import {CdkTreeModule} from '@angular/cdk/tree';
- import {NgModule} from '@angular/core';
- import {
-
- MatCardModule,
- MatIconModule,
- MatInputModule,
- MatListModule,
- MatMenuModule,
- MatPaginatorModule,
- MatProgressBarModule,
- MatSortModule,
- MatStepperModule,
- MatTableModule,
- MatTabsModule,
- MatToolbarModule
- } from '@angular/material';
-
- @NgModule({
- exports: [
- A11yModule,
- CdkStepperModule,
- CdkTableModule,
- CdkTreeModule,
- DragDropModule,
- MatCardModule,
- MatIconModule,
- MatInputModule,
- MatListModule,
- MatMenuModule,
- MatPaginatorModule,
- MatProgressBarModule,
- MatSortModule,
- MatStepperModule,
- MatTableModule,
- MatTabsModule,
- MatToolbarModule,
- PortalModule,
- ScrollingModule,
- ]
- })
- 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.
- import { Component, OnInit } from '@angular/core';
- import { User } from '../model/user';
- import { UserService } from '../service/user.service';
-
- @Component({
- selector: 'app-user',
- templateUrl: './user.component.html',
- styleUrls: ['./user.component.css']
- })
- export class UserComponent implements OnInit {
- allUser: User[] = [];
- page: number = 1;
- constructor(private service: UserService) { }
- displayedColumns: string[] = ['UserId', 'UserName', 'EmailId', 'Gender', 'Address', 'MobileNo', 'PinCode'];
- ngOnInit() {
- this.AllUserDetails();
- }
-
- AllUserDetails() {
- this.service.UserDetails(this.page).subscribe((res) => {
- this.allUser = res;
- });
- }
- onScroll() {
- this.page = this.page + 1;
- this.AllUserDetails();
- }
- }
Open user.component.html file and write the below code.
- <mat-toolbar color="accent" layout-align-md="center end">
- <span class="demo-toolbar">infinite Scroll Example</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;">
-
- <table mat-table [dataSource]="allUser">
- <ng-container matColumnDef="FirstName">
- <th mat-header-cell *matHeaderCellDef> FirstName </th>
- <td mat-cell *matCellDef="let element"> {{element.FirstName}} </td>
- </ng-container>
-
- <ng-container matColumnDef="LastName">
- <th mat-header-cell *matHeaderCellDef> LastName </th>
- <td mat-cell *matCellDef="let element"> {{element.LastName}} </td>
- </ng-container>
-
- <ng-container matColumnDef="UserId">
- <th mat-header-cell *matHeaderCellDef> UserId </th>
- <td mat-cell *matCellDef="let element"> {{element.UserId}} </td>
- </ng-container>
-
- <ng-container matColumnDef="UserName">
- <th mat-header-cell *matHeaderCellDef> UserName </th>
- <td mat-cell *matCellDef="let element"> {{element.UserName}} </td>
- </ng-container>
-
- <ng-container matColumnDef="EmailId">
- <th mat-header-cell *matHeaderCellDef> EmailId </th>
- <td mat-cell *matCellDef="let element"> {{element.EmailId}} </td>
- </ng-container>
-
- <ng-container matColumnDef="Gender">
- <th mat-header-cell *matHeaderCellDef> Gender </th>
- <td mat-cell *matCellDef="let element"> {{element.Gender ==0? 'Male' : 'Female'}} </td>
- </ng-container>
-
- <ng-container matColumnDef="Address">
- <th mat-header-cell *matHeaderCellDef> Address </th>
- <td mat-cell *matCellDef="let element"> {{element.Address}} </td>
- </ng-container>
- <ng-container matColumnDef="MobileNo">
- <th mat-header-cell *matHeaderCellDef> MobileNo </th>
- <td mat-cell *matCellDef="let element"> {{element.MobileNo}} </td>
- </ng-container>
- <ng-container matColumnDef="PinCode">
- <th mat-header-cell *matHeaderCellDef> PinCode </th>
- <td mat-cell *matCellDef="let element"> {{element.PinCode}} </td>
- </ng-container>
- <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
- <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
- </table>
Open user.component.css file and write the below code.
- th{
- background-color: #428BCA;
- color: white;
- width:200px;
- font-size: large;
- }
Open app.component.html file and write the below code.
- <div class="container">
- <app-user></app-user>
- </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.
Add namespace
- using System.Web.Http.Cors;
After that add the below code inside the Register method,
- var cors = new EnableCorsAttribute("*", "*", "*");
- 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.
Let's check full functionality,
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.