Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL

In this article  I'm going to perform deleting multiple rows with check boxes in Angular 9 using Web API with the help of an example. And the backend is a SQL Server database. Here I am using Web API to provide data connectivity between the database and the front end application. On the UI side, I will use bootstrap and angular material to create a rich, interactive , device-independent user experience for building a beautiful UI.
 
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 it. Here is Visual Studio Code download link:vDownload Visual Studio Code Editor
 
First, take a look at our output,
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Prerequisites
  1. Visual studio
  2. Sql Server
  3. Node.js version > 10
  4. Angular 9
  5. Visual studio code
  6. Bootstrap
  7. Angular material
Step 1 - Create a database and table
 
Create a database. Open SQL Server and create a new database and table. As you can see from the following query, I have created a database table called User Details.
  1. CREATE TABLE [dbo].[userdetails]   
  2.   (   
  3.      [userid]   [INT] IDENTITY(1, 1) NOT NULL,   
  4.      [username] [VARCHAR](50) NULL,   
  5.      [emailid]  [VARCHAR](150) NULL,   
  6.      [gender]   [VARCHAR](50) NULL,   
  7.      [address]  [VARCHAR](500) NULL,   
  8.      [mobileno] [VARCHAR](15) NULL,   
  9.      [pincode]  [VARCHAR](10) NULL,   
  10.      CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED ( [userid] ASC )WITH (   
  11.      pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,   
  12.      allow_row_locks = on, allow_page_locks = onON [PRIMARY]   
  13.   )   
  14. ON [PRIMARY]   
  15.   
  16. go   
Note
You can choose the size of the column according to your requirement.
 
Step 2 - Create a Web API Project

Now, we will create a Web API with the functionality of binding records from a database. Go to Visual Studio >> File >> New >> Project, and select Web Application.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Click OK and you will see the templates. Select the Web API template.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Click OK.
 
Step 3 - Add ADO.NET Entity Data Model
 
Now, Select Models folder >> Right click >> Add >> New Item >> select Data in left panel >> ADO.NET Entity Data Model,
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Click Add button
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Click Next button
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Give server name of SQL server and its credential then select database and test connection then click the ok button.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Click Next button
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Select UserDetails table and click the Finish button
 
Step 4 - Add API controller logic
 
Go to the Controller folder in our API Application and right-click >> Add >> Controller >> Select Web API 2 Controller-Empty
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Click Add button
 
Now we will write the logic for binding data and deleting record functionality. We will go to the controller class and set the routing to make it more user-friendly by writing the below code.
  1. using AngularApp.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Net;  
  7. using System.Net.Http;  
  8. using System.Web.Http;  
  9. namespace AngularApp.Controllers {  
  10.     [RoutePrefix("Api/User")]  
  11.     public class UserAPIController: ApiController {  
  12.         AngularDBEntities objEntity = new AngularDBEntities();  
  13.         [HttpGet]  
  14.         [Route("GetUserDetails")]  
  15.         public IQueryable < UserDetail > GetUser() {  
  16.                 try {  
  17.                     return objEntity.UserDetails;  
  18.                 } catch (Exception) {  
  19.                     throw;  
  20.                 }  
  21.             }  
  22.             [HttpPost]  
  23.             [Route("DeleteRecord")]  
  24.         public IHttpActionResult DeleteRecord(List < UserDetail > user) {  
  25.             string result = "";  
  26.             if (!ModelState.IsValid) {  
  27.                 return BadRequest(ModelState);  
  28.             }  
  29.             try {  
  30.                 result = DeleteData(user);  
  31.             } catch (Exception ex) {  
  32.                 throw;  
  33.             }  
  34.             return Ok(result);  
  35.         }  
  36.         private string DeleteData(List < UserDetail > users) {  
  37.             string str = "";  
  38.             try {  
  39.                 foreach(var item in users) {  
  40.                     UserDetail obj = new UserDetail();  
  41.                     obj.UserId = item.UserId;  
  42.                     obj.UserName = item.UserName;  
  43.                     obj.Gender = item.Gender;  
  44.                     obj.MobileNo = item.MobileNo;  
  45.                     obj.PinCode = item.PinCode;  
  46.                     obj.EmailId = item.EmailId;  
  47.                     var entry = objEntity.Entry(obj);  
  48.                     if (entry.State == EntityState.Detached) objEntity.UserDetails.Attach(obj);  
  49.                     objEntity.UserDetails.Remove(obj);  
  50.                 }  
  51.                 int i = objEntity.SaveChanges();  
  52.                 if (i > 0) {  
  53.                     str = "Records has been deleted";  
  54.                 } else {  
  55.                     str = "Records deletion has been faild";  
  56.                 }  
  57.             } catch (Exception) {  
  58.                 throw;  
  59.             }  
  60.             return str;  
  61.         }  
  62.     }  
  63. }  
Now, our API has been completed and as you may see from the above code, it has the functionality to bind and delete records to the table.
 
Step 5 - Install Angular CLI
 
Now we will install angular CLI through the below command. But before that just check whether Node and NPM are installed or not. And also we are using Visual Studio code as we are writing Angular code for UI applications.  So first, make sure it's installed. If you have not installed it then go to this link for download.
 
Let's install CLI to open a cmd and run the following command to install
 
npm install -g @angular/cli
 
Step 6 - Create am Anguglar project

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 MultiselectDelete.
 
ng new MultiselectDelete

After that, hit ENTER. It will take a while to create the project. 
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
...... ........................
 Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Once created, the project should look like this.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Step 7 - Check Angular dependency
 
Go into package.json file and check the Angular dependency.
 
 Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Step 8 - Install and Configure Angular Material Theme
 
As I mentioned 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.
 
If you have an existing Angular Project, Open Terminal/Command Prompt in the same folder as project and Write,
 
ng add @angular/material
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
After installing successfully, we can check in the package.json file,
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Step 9 - Install bootstrap
 
Now, we will install bootstrap to building a beautiful UI of our angular application.
 
npm install bootstrap --save
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Step 11 - Create Components
 
Now, we can create some components to provide the UI.
 
I'm going to create a new component, User and Add User.
 
Go to the TERMINAL and go our Angular project location using the following command.
 
ng g c user
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Step 12 - Create Service
 
Now, we will create a service.
 
Open the TERMINAL and write the below command,
 
ng g s user
 
Press ENTER and you will see two service files.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Step 13 - Create a model class
 
Now, we create a class like model class.
 
Open TERMINAL and write the below command,
 
ng g class UserDetails
  1. export class UserDetail {  
  2.     UserId: number;  
  3.     UserName: string;  
  4.     EmailId: string;  
  5.     Gender: string;  
  6.     Address: string;  
  7.     MobileNo: string;  
  8.     PinCode: string;  
  9. }  
Step 14 - Implement component UI
 
Now we will write our logic to bind and delete records.
 
Go inside the user folder and open user.component.html file and write the below code.
  1. <div class="container">  
  2.     <h1>Multi select delete examample in angular</h1>  
  3.     <hr>  
  4.         <div class="row push-right">  
  5.             <input type="button" class="btn btn-danger" (click)="DeleteData()" value="Delete Education">  
  6.                 <br>  
  7.                 </div>  
  8.                 <br>  
  9.                     <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">  
  10.                         <!-- Checkbox Column -->  
  11.                         <ng-container matColumnDef="select">  
  12.                             <th style="width: 100px;" mat-header-cell *matHeaderCellDef>  
  13.                                 <mat-checkbox (change)="$event ? masterToggle() : null"  
  14. [checked]="selection.hasValue() && isAllSelected()"  
  15. [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>  
  16.                             </th>  
  17.                             <td mat-cell *matCellDef="let row">  
  18.                                 <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null"  
  19. [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)"></mat-checkbox>  
  20.                             </td>  
  21.                         </ng-container>  
  22.                         <ng-container matColumnDef="UserId">  
  23.                             <th style="width: 100px;" mat-header-cell *matHeaderCellDef> No. </th>  
  24.                             <td mat-cell *matCellDef="let element"> {{element.UserId}} </td>  
  25.                         </ng-container>  
  26.                         <!-- User Name Column -->  
  27.                         <ng-container matColumnDef="UserName">  
  28.                             <th style="width: 150px;" mat-header-cell *matHeaderCellDef> User Name </th>  
  29.                             <td mat-cell *matCellDef="let element"> {{element.UserName}} </td>  
  30.                         </ng-container>  
  31.                         <!-- EmailId Column -->  
  32.                         <ng-container matColumnDef="EmailId">  
  33.                             <th style="width: 150px;" mat-header-cell *matHeaderCellDef> EmailId </th>  
  34.                             <td mat-cell *matCellDef="let element"> {{element.EmailId}} </td>  
  35.                         </ng-container>  
  36.                         <!-- Gender Column -->  
  37.                         <ng-container matColumnDef="Gender">  
  38.                             <th style="width: 150px;" mat-header-cell *matHeaderCellDef> Gender </th>  
  39.                             <td mat-cell *matCellDef="let element"> {{element.Gender.trim()}} </td>  
  40.                         </ng-container>  
  41.                         <!-- Mobile Column -->  
  42.                         <ng-container matColumnDef="MobileNo">  
  43.                             <th mat-header-cell *matHeaderCellDef> MobileNo </th>  
  44.                             <td mat-cell *matCellDef="let element"> {{element.MobileNo}} </td>  
  45.                         </ng-container>  
  46.                         <!-- Address Column -->  
  47.                         <ng-container matColumnDef="Address">  
  48.                             <th mat-header-cell *matHeaderCellDef> Address </th>  
  49.                             <td mat-cell *matCellDef="let element"> {{element.Address}} </td>  
  50.                         </ng-container>  
  51.                         <!-- Pine Code Column -->  
  52.                         <ng-container matColumnDef="PinCode">  
  53.                             <th mat-header-cell *matHeaderCellDef> PinCode </th>  
  54.                             <td mat-cell *matCellDef="let element"> {{element.PinCode}} </td>  
  55.                         </ng-container>  
  56.                         <tr mat-header-row *matHeaderRowDef="displayedColumns"  
  57. style="background-color:darkblue;"></tr>  
  58.                         <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)"></tr>  
  59.                     </table>  
  60.                 </div>  
And now open user.component.ts and first import the necessary library and then write the below code. 
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     UserDetail  
  7. } from '../user';  
  8. import {  
  9.     SelectionModel  
  10. } from '@angular/cdk/collections';  
  11. import {  
  12.     MatTableDataSource  
  13. } from '@angular/material/table';  
  14. import {  
  15.     UserService  
  16. } from '../user.service';  
  17. @Component({  
  18.     selector: 'app-user',  
  19.     templateUrl: './user.component.html',  
  20.     styleUrls: ['./user.component.css']  
  21. })  
  22. export class UserComponent implements OnInit {  
  23.     TotalRow: number;  
  24.     displayedColumns: string[] = ['select''UserId''UserName''EmailId''Gender''Address''MobileNo''PinCode'];  
  25.     dataSource: MatTableDataSource < UserDetail > ;  
  26.     selection = new SelectionModel < UserDetail > (true, []);  
  27.     constructor(private service: UserService) {}  
  28.     ngOnInit(): void {  
  29.         this.LoadData();  
  30.     }  
  31.     LoadData() {  
  32.         this.service.getUsers().subscribe(result => {  
  33.             this.dataSource = new MatTableDataSource(result);  
  34.         })  
  35.     }  
  36.     /** Whether the number of selected elements matches the total number of rows. */  
  37.     isAllSelected() {  
  38.         const numSelected = this.selection.selected.length;  
  39.         const numRows = !!this.dataSource && this.dataSource.data.length;  
  40.         return numSelected === numRows;  
  41.     }  
  42.     /** Selects all rows if they are not all selected; otherwise clear selection. */  
  43.     masterToggle() {  
  44.         this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(r => this.selection.select(r));  
  45.     }  
  46.     /** The label for the checkbox on the passed row */  
  47.     checkboxLabel(row: UserDetail): string {  
  48.         if (!row) {  
  49.             return `${this.isAllSelected() ? 'select' : 'deselect'} all`;  
  50.         }  
  51.         return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.UserId + 1}`;  
  52.     }  
  53.     DeleteData() {  
  54.         debugger;  
  55.         const numSelected = this.selection.selected;  
  56.         if (numSelected.length > 0) {  
  57.             if (confirm("Are you sure to delete items ")) {  
  58.                 this.service.deleteData(numSelected).subscribe(result => {  
  59.                     alert(result);  
  60.                     this.LoadData();  
  61.                 })  
  62.             }  
  63.         } else {  
  64.             alert("Select at least one row");  
  65.         }  
  66.     }  
  67. }  
Open user.component.css and then write the below css code.
  1. .mat-header-cell{  
  2.    color:white;  
  3. }  
Step 16 - Write logic of service for consuming api
 
Now, open user.service.ts and first import the necessary class and libraries and then make calls to the WebAPI methods.
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Observable  
  6. } from 'rxjs';  
  7. import {  
  8.     UserDetail  
  9. } from './user';  
  10. import {  
  11.     HttpClient,  
  12.     HttpHeaders  
  13. } from '@angular/common/http';  
  14. @Injectable({  
  15.     providedIn: 'root'  
  16. })  
  17. export class UserService {  
  18.     apiUrl: string = "http://localhost:50685/Api/User/";  
  19.     constructor(private http: HttpClient) {}  
  20.     getUsers(): Observable < UserDetail[] > {  
  21.         return this.http.get < UserDetail[] > (`${this.apiUrl}GetUserDetails`);  
  22.     }  
  23.     deleteData(user: UserDetail[]): Observable < string > {  
  24.         const httpOptions = {  
  25.             headers: new HttpHeaders({  
  26.                 'Content-Type''application/json'  
  27.             })  
  28.         };  
  29.         return this.http.post < string > (`${this.apiUrl}DeleteRecord/`, user, httpOptions);  
  30.     }  
  31. }  
Step 17 - Calling the selector page or parant page
 
Go to app.component.html page and remove the existing html code and add the below selector:
  1. <app-user></app-user>   
Finally, our coding part also has been completed.
 
Step 18 - Set CORS (Cross-Origin Resource Sharing)
 
Go to the Web API project.
 
Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
After that, go to the App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
 
Add namespace 
  1. var cors = new EnableCorsAttribute("*""*""*"); //origins,headers,methods  
  2. config.EnableCors(cors);  
Step 19 - Run
 
We have completed all needed code functionality for bind and delete operations. 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 created with bind and delete operations.
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
Click delete data button without selecting any row. 
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
 
Now select the row which have you deleted. 
 
Deleting Multiple Rows With Checkboxes In Angular 9 With Web API And SQL
Click on delete button
 

Conclusion

 
We have completed performing a bind and delete operation with multi select checkbox in Angular 9 using Angular material UI and Web API for user details.
 
We have started by installing and creating the create-angular-app then used it to create our Angular project. Next, we have installed bootstrap in our application. After that we installed the angular material to display user details and used the get(),post() methods for the HTTP request.
 
I hope you will enjoy this article. You are always welcome to ask any query and leave a comment.


Similar Articles