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:v
Download Visual Studio Code Editor
First, take a look at our output,
Prerequisites
- Visual studio
- Sql Server
- Node.js version > 10
- Angular 9
- Visual studio code
- Bootstrap
- 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.
- CREATE TABLE [dbo].[userdetails]
- (
- [userid] [INT] IDENTITY(1, 1) NOT NULL,
- [username] [VARCHAR](50) NULL,
- [emailid] [VARCHAR](150) NULL,
- [gender] [VARCHAR](50) NULL,
- [address] [VARCHAR](500) NULL,
- [mobileno] [VARCHAR](15) NULL,
- [pincode] [VARCHAR](10) NULL,
- CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED ( [userid] ASC )WITH (
- pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,
- allow_row_locks = on, allow_page_locks = on) ON [PRIMARY]
- )
- ON [PRIMARY]
-
- 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.
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 Models folder >> Right click >> Add >> New Item >> select Data in left panel >> ADO.NET Entity Data Model,
Click Add button
Click Next button
Give server name of SQL server and its credential then select database and test connection then click the ok button.
Click Next button
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
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.
- using AngularApp.Models;
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace AngularApp.Controllers {
- [RoutePrefix("Api/User")]
- public class UserAPIController: ApiController {
- AngularDBEntities objEntity = new AngularDBEntities();
- [HttpGet]
- [Route("GetUserDetails")]
- public IQueryable < UserDetail > GetUser() {
- try {
- return objEntity.UserDetails;
- } catch (Exception) {
- throw;
- }
- }
- [HttpPost]
- [Route("DeleteRecord")]
- public IHttpActionResult DeleteRecord(List < UserDetail > user) {
- string result = "";
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- try {
- result = DeleteData(user);
- } catch (Exception ex) {
- throw;
- }
- return Ok(result);
- }
- private string DeleteData(List < UserDetail > users) {
- string str = "";
- try {
- foreach(var item in users) {
- UserDetail obj = new UserDetail();
- obj.UserId = item.UserId;
- obj.UserName = item.UserName;
- obj.Gender = item.Gender;
- obj.MobileNo = item.MobileNo;
- obj.PinCode = item.PinCode;
- obj.EmailId = item.EmailId;
- var entry = objEntity.Entry(obj);
- if (entry.State == EntityState.Detached) objEntity.UserDetails.Attach(obj);
- objEntity.UserDetails.Remove(obj);
- }
- int i = objEntity.SaveChanges();
- if (i > 0) {
- str = "Records has been deleted";
- } else {
- str = "Records deletion has been faild";
- }
- } catch (Exception) {
- throw;
- }
- return str;
- }
- }
- }
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.
...... ........................
Once created, the project should look like this.
Step 7 - Check Angular dependency
Go into package.json file and check the Angular dependency.
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,
After installing successfully, we can check in the package.json file,
Step 9 - Install bootstrap
Now, we will install bootstrap to building a beautiful UI of our angular application.
npm install bootstrap --save
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
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.
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
- export class UserDetail {
- UserId: number;
- UserName: string;
- EmailId: string;
- Gender: string;
- Address: string;
- MobileNo: string;
- PinCode: string;
- }
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.
- <div class="container">
- <h1>Multi select delete examample in angular</h1>
- <hr>
- <div class="row push-right">
- <input type="button" class="btn btn-danger" (click)="DeleteData()" value="Delete Education">
- <br>
- </div>
- <br>
- <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
- <!-- Checkbox Column -->
- <ng-container matColumnDef="select">
- <th style="width: 100px;" mat-header-cell *matHeaderCellDef>
- <mat-checkbox (change)="$event ? masterToggle() : null"
- [checked]="selection.hasValue() && isAllSelected()"
- [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
- </th>
- <td mat-cell *matCellDef="let row">
- <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null"
- [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)"></mat-checkbox>
- </td>
- </ng-container>
- <ng-container matColumnDef="UserId">
- <th style="width: 100px;" mat-header-cell *matHeaderCellDef> No. </th>
- <td mat-cell *matCellDef="let element"> {{element.UserId}} </td>
- </ng-container>
- <!-- User Name Column -->
- <ng-container matColumnDef="UserName">
- <th style="width: 150px;" mat-header-cell *matHeaderCellDef> User Name </th>
- <td mat-cell *matCellDef="let element"> {{element.UserName}} </td>
- </ng-container>
- <!-- EmailId Column -->
- <ng-container matColumnDef="EmailId">
- <th style="width: 150px;" mat-header-cell *matHeaderCellDef> EmailId </th>
- <td mat-cell *matCellDef="let element"> {{element.EmailId}} </td>
- </ng-container>
- <!-- Gender Column -->
- <ng-container matColumnDef="Gender">
- <th style="width: 150px;" mat-header-cell *matHeaderCellDef> Gender </th>
- <td mat-cell *matCellDef="let element"> {{element.Gender.trim()}} </td>
- </ng-container>
- <!-- Mobile Column -->
- <ng-container matColumnDef="MobileNo">
- <th mat-header-cell *matHeaderCellDef> MobileNo </th>
- <td mat-cell *matCellDef="let element"> {{element.MobileNo}} </td>
- </ng-container>
- <!-- Address Column -->
- <ng-container matColumnDef="Address">
- <th mat-header-cell *matHeaderCellDef> Address </th>
- <td mat-cell *matCellDef="let element"> {{element.Address}} </td>
- </ng-container>
- <!-- Pine Code Column -->
- <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"
- style="background-color:darkblue;"></tr>
- <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)"></tr>
- </table>
- </div>
And now open user.component.ts and first import the necessary library and then write the below code.
- import {
- Component,
- OnInit
- } from '@angular/core';
- import {
- UserDetail
- } from '../user';
- import {
- SelectionModel
- } from '@angular/cdk/collections';
- import {
- MatTableDataSource
- } from '@angular/material/table';
- import {
- UserService
- } from '../user.service';
- @Component({
- selector: 'app-user',
- templateUrl: './user.component.html',
- styleUrls: ['./user.component.css']
- })
- export class UserComponent implements OnInit {
- TotalRow: number;
- displayedColumns: string[] = ['select', 'UserId', 'UserName', 'EmailId', 'Gender', 'Address', 'MobileNo', 'PinCode'];
- dataSource: MatTableDataSource < UserDetail > ;
- selection = new SelectionModel < UserDetail > (true, []);
- constructor(private service: UserService) {}
- ngOnInit(): void {
- this.LoadData();
- }
- LoadData() {
- this.service.getUsers().subscribe(result => {
- this.dataSource = new MatTableDataSource(result);
- })
- }
-
- isAllSelected() {
- const numSelected = this.selection.selected.length;
- const numRows = !!this.dataSource && this.dataSource.data.length;
- return numSelected === numRows;
- }
-
- masterToggle() {
- this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(r => this.selection.select(r));
- }
-
- checkboxLabel(row: UserDetail): string {
- if (!row) {
- return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
- }
- return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.UserId + 1}`;
- }
- DeleteData() {
- debugger;
- const numSelected = this.selection.selected;
- if (numSelected.length > 0) {
- if (confirm("Are you sure to delete items ")) {
- this.service.deleteData(numSelected).subscribe(result => {
- alert(result);
- this.LoadData();
- })
- }
- } else {
- alert("Select at least one row");
- }
- }
- }
Open user.component.css and then write the below css code.
- .mat-header-cell{
- color:white;
- }
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.
- import {
- Injectable
- } from '@angular/core';
- import {
- Observable
- } from 'rxjs';
- import {
- UserDetail
- } from './user';
- import {
- HttpClient,
- HttpHeaders
- } from '@angular/common/http';
- @Injectable({
- providedIn: 'root'
- })
- export class UserService {
- apiUrl: string = "http://localhost:50685/Api/User/";
- constructor(private http: HttpClient) {}
- getUsers(): Observable < UserDetail[] > {
- return this.http.get < UserDetail[] > (`${this.apiUrl}GetUserDetails`);
- }
- deleteData(user: UserDetail[]): Observable < string > {
- const httpOptions = {
- headers: new HttpHeaders({
- 'Content-Type': 'application/json'
- })
- };
- return this.http.post < string > (`${this.apiUrl}DeleteRecord/`, user, httpOptions);
- }
- }
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:
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.
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
- var cors = new EnableCorsAttribute("*", "*", "*");
- 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.
Click delete data button without selecting any row.
Now select the row which have you deleted.
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.