Filtration, Sorting, And Pagination In Angular 7 Using Web API And SQL Server

A Web API is used to provide data connectivity between the database and the front-end application. On the UI side, I will use the Angular Material theme to create a rich, interactive, and device-independent user experience.

I'm using Visual Studio Code as a tool to build my application. If you don't have Visual Studio Code in your system, then first, you have to download and install. Here is Visual Studio Code download link: Download Visual Studio Code Editor

You can read my previous articles related to Angular 7 from the following links.

Step 1. Create a database table

Create a database. Open SQL Server and create a new database table. As you can see from the following image, I create a database table called UserDetails with 7 columns.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server

  1. insert into UserDetails values('Mithilesh','[email protected]','0','Hyderabad','8227382372','123456')  
  2. insert into UserDetails values('Jon','[email protected]','0','Hyderabad','8227382372','123456')  
  3. insert into UserDetails values('jony','[email protected]','0','newyork','8293282272','187456')  
  4. insert into UserDetails values('Raju','[email protected]','0','tamilnadu','8227382372','123456')  
  5. insert into UserDetails values('Suresh','[email protected]','0','Delhi','8227382372','128956')  
  6. insert into UserDetails values('Mona','[email protected]','1','Hyderabad','8398732372','983456')  
  7. insert into UserDetails values('Ruma','[email protected]','1','Banglore','8227382372','123456')  
  8. insert into UserDetails values('Shaid','[email protected]','0','Patna','9823798323','123456')  
  9. insert into UserDetails values('Bharti','[email protected]','1','Jaypur','8227382372','654321')  
  10. insert into UserDetails values('Sohan','[email protected]','0','Srinagar','847623298','123456')  
  11. insert into UserDetails values('Sukesh','[email protected]','0','Hyderabad','8227382372','123456')  
  12. insert into UserDetails values('Kabir','[email protected]','0','Mumbai','982749233','123456')  
  13. insert into UserDetails values('Rmya','[email protected]','1','Vanarasi','8227382372','834846')  

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 bind 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.

 

Filtration, Shorting, Pagination 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.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server
 
Filtration, Shorting, Pagination 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.

Filtration, Shorting, Pagination 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 code to perform the binding operation.

Go to the Controllers folder in our API Application and right-click >> Add >> Controller >> Select Web API 2 Controller-Empty.

Filtration, Shorting, Pagination 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. [RoutePrefix("Api/UserAPI")]  
  2.   public class UserController : ApiController  
  3.   {  
  4.       [HttpGet]  
  5.       [Route("AllUser")]  
  6.       public IEnumerable<UserDetail> UserDetails()  
  7.       {  
  8.           IEnumerable<UserDetail> lstUser = new List<UserDetail>();  
  9.           string response = "";  
  10.           try  
  11.           {  
  12.               using (CRUDDBEntities objEntity = new CRUDDBEntities())  
  13.               {  
  14.                   lstUser = objEntity.UserDetails.ToList();  
  15.               }  
  16.           }  
  17.           catch (Exception ex)  
  18.           {  
  19.               response = ex.ToString();  
  20.           }  
  21.           return lstUser;  
  22.       }  
  23.   }  

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

Step 5. Build UI Application

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

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

Open the command prompt, and type the below code, and press ENTER:

npm install -g @angular/cli

Now, open Visual Studio Code and create a project.

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

ng new BindRecords

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

Once created, the project should look like this.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

Now, we will create components to provide the UI.

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

Go to the TERMINAL and go our angular project location using the following command:

cd projectName

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

ng g c employee

Press ENTER.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

Note
You can use see the component is created.

Step 6. Create an Interface

Now, we create an interface like model class.

Open TERMINAL and write the below command:

ng g interface model/IUser --spec=false

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

Now, write all properties of the Employee class related to an employee that matches with the database.

  1. export interface IUser {  
  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 a Service


Now, we will create a service.

Open the TERMINAL and write the below command:

ng g s employee --spec=false 

Press ENTER and you will see service files.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

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

  1. import { Injectable } from '@angular/core';  
  2. import { IUser } from './model/iuser';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Observable } from 'rxjs';  
  5.   
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class EmployeeService {  
  10.   url = "http://localhost:50468/";  
  11.   constructor(private http: HttpClient) { }  
  12.   AllUserDetails(): Observable<IUser[]> {  
  13.     return this.http.get<IUser[]>(this.url + 'Api/UserAPI/AllUser')  
  14.   }  
  15. }  

Step 8. Install and Configure Angular Material Theme

As I said earlier, we will use 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 installed successfully, we can check in the package.json file.
 
Filtration, Shorting, Pagination 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

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

Open angularmaterial.ts class and write the below code.

  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.   MatAutocompleteModule,  
  11.   MatBadgeModule,  
  12.   MatBottomSheetModule,  
  13.   MatButtonModule,  
  14.   MatButtonToggleModule,  
  15.   MatCardModule,  
  16.   MatCheckboxModule,  
  17.   MatChipsModule,  
  18.   MatDatepickerModule,  
  19.   MatDialogModule,  
  20.   MatDividerModule,  
  21.   MatExpansionModule,  
  22.   MatGridListModule,  
  23.   MatIconModule,  
  24.   MatInputModule,  
  25.   MatListModule,  
  26.   MatMenuModule,  
  27.   MatNativeDateModule,  
  28.   MatPaginatorModule,  
  29.   MatProgressBarModule,  
  30.   MatProgressSpinnerModule,  
  31.   MatRadioModule,  
  32.   MatRippleModule,  
  33.   MatSelectModule,  
  34.   MatSidenavModule,  
  35.   MatSliderModule,  
  36.   MatSlideToggleModule,  
  37.   MatSnackBarModule,  
  38.   MatSortModule,  
  39.   MatStepperModule,  
  40.   MatTableModule,  
  41.   MatTabsModule,  
  42.   MatToolbarModule,  
  43.   MatTooltipModule,  
  44.   MatTreeModule,  
  45. } from '@angular/material';  
  46.   
  47. @NgModule({  
  48.   exports: [  
  49.     A11yModule,  
  50.     CdkStepperModule,  
  51.     CdkTableModule,  
  52.     CdkTreeModule,  
  53.     DragDropModule,  
  54.     MatAutocompleteModule,  
  55.     MatBadgeModule,  
  56.     MatBottomSheetModule,  
  57.     MatButtonModule,  
  58.     MatButtonToggleModule,  
  59.     MatCardModule,  
  60.     MatCheckboxModule,  
  61.     MatChipsModule,  
  62.     MatStepperModule,  
  63.     MatDatepickerModule,  
  64.     MatDialogModule,  
  65.     MatDividerModule,  
  66.     MatExpansionModule,  
  67.     MatGridListModule,  
  68.     MatIconModule,  
  69.     MatInputModule,  
  70.     MatListModule,  
  71.     MatMenuModule,  
  72.     MatNativeDateModule,  
  73.     MatPaginatorModule,  
  74.     MatProgressBarModule,  
  75.     MatProgressSpinnerModule,  
  76.     MatRadioModule,  
  77.     MatRippleModule,  
  78.     MatSelectModule,  
  79.     MatSidenavModule,  
  80.     MatSliderModule,  
  81.     MatSlideToggleModule,  
  82.     MatSnackBarModule,  
  83.     MatSortModule,  
  84.     MatTableModule,  
  85.     MatTabsModule,  
  86.     MatToolbarModule,  
  87.     MatTooltipModule,  
  88.     MatTreeModule,  
  89.     PortalModule,  
  90.     ScrollingModule,  
  91.   ]  
  92. })  
  93. export class AngularmaterialModule { }  

Step 9. Add library in app.module

Now, open app.module.ts class and write the below code.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppRoutingModule } from './app-routing.module';  
  4. import { AppComponent } from './app.component';  
  5. import { EmployeeComponent } from './employee/employee.component';  
  6. import { AngularmaterialModule } from './material/angularmaterial/angularmaterial.module';  
  7. import { EmployeeService } from './employee.service';  
  8. import { HttpClientModule } from '@angular/common/http';  
  9. import {BrowserAnimationsModule} from '@angular/platform-browser/animations';  
  10.   
  11. @NgModule({  
  12.   declarations: [  
  13.     AppComponent,  
  14.     EmployeeComponent  
  15.   ],  
  16.   imports: [  
  17.     BrowserModule,  
  18.     HttpClientModule,  
  19.     BrowserAnimationsModule,  
  20.     AngularmaterialModule,  
  21.     AppRoutingModule  
  22.   ],  
  23.   providers: [EmployeeService],  
  24.   bootstrap: [AppComponent]  
  25. })  
  26. export class AppModule { }  

Step 10. Add Filtration, Pagination and Shorting functionality

We have added the necessary library . Now, we will design ui using angular material table. Let us first understand how it uses angular material line by line.

mat-table and provide data

Begin by adding the <table mat-table> component to your template and passing in data.

The simplest way to provide data to the table is by passing a data array to the table's dataSource input. The table will take the array and render a row for each object in the data array.

<table mat-table [dataSource]="dataSource"> ...</table>

Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table's rendered rows by calling its renderRows()method.

Define the column templates

The first step to writing the data-table template is to define the columns. A column definition is specified via an <ng-container>with the matColumnDef directive, giving the column a name. Each column definition can contain a header-cell template (matHeaderCellDef) and data-cell template (matCellDef)

  1. <ng-container matColumnDef="FirstName">  
  2.    <th mat-header-cell *matHeaderCellDef mat-sort-header> FirstName </th>  
  3.    <td mat-cell *matCellDef="let element"> {{element.FirstName}} </td>  
  4. </ng-container>  

The set of columns defined represent the columns that are available to be rendered. The specific columns rendered in a given row, and their order, are specified on the row.

DataSource

The DataSource is meant to serve a place to encapsulate any sorting, filtering, pagination, and data retrieval logic specific to the application. More details go this link

Pagination

To paginate the table's data, add a <mat-paginator> after the table.

The MatPaginator is one provided solution to paginating your table's data,

Sorting

To add sorting behavior to the table, add the matSort directive to the table it will automatically listen for sorting changes and change the order of data rendered by the table and add mat-sort-header to each column header cell that should trigger sorting. Note that you have to import MatSortModule in order to initialize the matSort directive

Filtering

Angular Material does not provide a specific component to be used for filtering the MatTable since there is no single common approach to adding a filter UI to table data.

A general strategy is to add an input where users can type in a filter string and listen to this input to change what data is offered from the data source to the table.

Step 11. Implement component class

Now we will write code for perform the bind records, filtration, pagination and shorting functionality. Open employee.component.ts file and below code.

  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2. import { IUser } from '../model/iuser';  
  3. import { MatTableDataSource, MatSort, MatPaginator } from '@angular/material';  
  4. import { EmployeeService } from '../employee.service';  
  5.   
  6. @Component({  
  7.   selector: 'app-employee',  
  8.   templateUrl: './employee.component.html',  
  9.   styleUrls: ['./employee.component.css']  
  10. })  
  11. export class EmployeeComponent implements OnInit {  
  12.   
  13.   allUser:IUser[];  
  14.   dataSource: MatTableDataSource<IUser>;  
  15.   displayedColumns: string[] = ['UserId''UserName''EmailId''Gender','Address','MobileNo','PinCode'];  
  16.   @ViewChild(MatPaginator) paginator: MatPaginator;  
  17.   @ViewChild(MatSort) sort: MatSort;  
  18.   
  19. constructor(private service: EmployeeService,){  
  20.   this.service.AllUserDetails().subscribe(data =>{  
  21.     this.dataSource = new MatTableDataSource(data);  
  22.     this.dataSource.paginator = this.paginator;  
  23.     this.dataSource.sort = this.sort;  
  24.   });  
  25. }  
  26.   ngOnInit() {  
  27.     this.dataSource.paginator = this.paginator;  
  28.     this.dataSource.sort = this.sort;  
  29.      
  30.   }  
  31.   
  32.   applyFilter(filterValue: string) {  
  33.     this.dataSource.filter = filterValue.trim().toLowerCase();  
  34.   
  35.     if (this.dataSource.paginator) {  
  36.       this.dataSource.paginator.firstPage();  
  37.     }  
  38.   }  
  39. }  

Open employee.component.html file and write below code.

  1. <h2>User Details</h2>  
  2. <mat-form-field>  
  3.   <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">  
  4. </mat-form-field>  
  5.   
  6. <div class="mat-elevation-z8">  
  7.   <table mat-table [dataSource]="dataSource" matSort>  
  8.   
  9.     <ng-container matColumnDef="UserId">  
  10.       <th mat-header-cell *matHeaderCellDef mat-sort-header> UserId </th>  
  11.       <td mat-cell *matCellDef="let user"> {{user.UserId}} </td>  
  12.     </ng-container>  
  13.   
  14.     <ng-container matColumnDef="UserName">  
  15.       <th mat-header-cell *matHeaderCellDef mat-sort-header> User Name </th>  
  16.       <td mat-cell *matCellDef="let user"> {{user.UserName}} </td>  
  17.     </ng-container>  
  18.   
  19.         <ng-container matColumnDef="EmailId">  
  20.           <th mat-header-cell *matHeaderCellDef mat-sort-header> EmailId </th>  
  21.           <td mat-cell *matCellDef="let user"> {{user.EmailId}} </td>  
  22.         </ng-container>  
  23.   
  24.     <ng-container matColumnDef="Gender">  
  25.       <th mat-header-cell *matHeaderCellDef mat-sort-header> Gender </th>  
  26.       <td mat-cell *matCellDef="let user"> {{user.Gender ==0? 'Male' : 'Female'}} </td>  
  27.     </ng-container>  
  28.   
  29.         <ng-container matColumnDef="Address">  
  30.           <th mat-header-cell *matHeaderCellDef mat-sort-header> Address </th>  
  31.           <td mat-cell *matCellDef="let user"> {{user.Address}} </td>  
  32.         </ng-container>  
  33.   
  34.         <ng-container matColumnDef="MobileNo">  
  35.           <th mat-header-cell *matHeaderCellDef mat-sort-header> Mobile No </th>  
  36.           <td mat-cell *matCellDef="let user"> {{user.MobileNo}} </td>  
  37.         </ng-container>  
  38.   
  39.         <ng-container matColumnDef="PinCode">  
  40.           <th mat-header-cell *matHeaderCellDef mat-sort-header> PinCode </th>  
  41.           <td mat-cell *matCellDef="let user"> {{user.PinCode}} </td>  
  42.         </ng-container>  
  43.   
  44.     <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>  
  45.     <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>  
  46.   </table>  
  47.   
  48.   <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>  
  49. </div>  

Now we have completed all code functionality now we will run the out project but before that we set 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.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

Add namespace

  1. using System.Web.Http.Cors;  

After that add below code inside 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 functiolity. 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 created.

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

Let's check full functionality,

Filtration, Shorting, Pagination In Angular 7 Using Web API And SQL Server 

We've finished performing bind records, pagination, sorting and filtration in an Angular 7 using Web API functionality. The app uses a Web API to provide data access from SQL Server. 

Thank you for reading my article.


Similar Articles