Angular 11 CURD Application Using Web API With Material Design

In this article, I am going to explain how to perform simple CURD operations using Angular11 and Web API with examples as well as how to implement cascading dropdown, searching, sorting, and pagination using Angular 11. In this tutorial, we will use the SQL Server database and for the attractive and responsive user interface for our Web app, we will use the Angular Material theme. Here, we will create a WEB API and will consume the created API using Angular 11.


In this tutorial, we are using Visual Studio 2019 and explaining how to create components, services, routes, pipes, searching, sorting, pagination in a simple way so it would be easy to understand for beginners.

Requirement

  1. Create a simple CURD operation using Angular 11 and WEB API.

  2. Use Angular Material theme and use maximum angular material controls to implement CURD operation using Angular 11 like a radio button, date picker or calendar control, textbox, dropdown control and etc.

  3. Implement cascading dropdown using angular 11.




Implementation

In this article we will create a CURD operation to store basic details of employees, So, let's start with a database and create a new database and table using SQL Server.


Step 1

Here, we will create 4 different tables for store information of employees as well as store information of the country, state, and city for cascading dropdown.


Table Employee

CREATE TABLE [dbo].[tblEmployeeMaster] (  
[EmpId] INT IDENTITY (1, 1) NOT NULL,  
[FirstName] VARCHAR (50) NULL,  
[LastName] VARCHAR (50) NULL,  
[DateofBirth] DATETIME NULL,  
[EmailId] NVARCHAR (50) NULL,  
[Gender] NCHAR (10) NULL,  
[CountryId] INT NULL,  
[StateId] INT NULL,  
[Cityid] INT NULL,  
[Address] VARCHAR (100) NULL,  
[Pincode] VARCHAR (50) NULL,  
CONSTRAINT [PK_tblEmployeeMaster] PRIMARY KEY CLUSTERED ([EmpId] ASC)  
);  


Country

CREATE TABLE [dbo].[CountryMaster] (  
[CountryId] INT IDENTITY (1, 1) NOT NULL,  
[CountryName] VARCHAR (50) NULL,  
CONSTRAINT [PK_CountryMaster] PRIMARY KEY CLUSTERED ([CountryId] ASC)  
);  


State

CREATE TABLE [dbo].[StateMaster] (  
[StateId] INT IDENTITY (1, 1) NOT NULL,  
[StateName] VARCHAR (50) NULL,  
[CountryId] INT NOT NULL,  
CONSTRAINT [PK_StateMaster] PRIMARY KEY CLUSTERED ([StateId] ASC)  
);  


City

CREATE TABLE [dbo].[CityMaster] (  
[Cityid] INT IDENTITY (1, 1) NOT NULL,  
[CityName] VARCHAR (50) NULL,  
[StateId] INT NOT NULL,  
[CountryId] INT NOT NULL,  
CONSTRAINT [PK_CityMaster] PRIMARY KEY CLUSTERED ([Cityid] ASC)  
);  

Now, Please add a few sample records into the country, state, and city table for demonstration.


INSERT [dbo].[CountryMaster] ([CountryName]) VALUES (N'India')    
INSERT [dbo].[CountryMaster] ([CountryName]) VALUES (N'United States')   

INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Andhra Pradesh', 1)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Gujarat', 1)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Kerala', 1)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Alabama', 2)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Hawaii', 2)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Texas', 2)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'New Mexico', 2)    
INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'New York', 2)   

INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Visakhapatnam', 1, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vijayawada', 1, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Guntur', 1, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Nellore', 1, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kurnool', 1, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Ahmedabad', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Surat', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vadodara', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Rajkot', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Bhavnagar', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Jamnagar', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Junagadh', 2, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Thiruvananthapuram', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kochi', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kozhikode', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kollam', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kannur', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Malappuram', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vatakara', 3, 1)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Adamsville', 4, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Addison', 4, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Allgood', 4, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Auburn', 4, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Honolulu', 5, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'East Honolulu', 5, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kahului', 5, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Abernathy', 6, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Alton', 6, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Barstow', 6, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Bellmead', 6, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Angel Fire', 7, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Capitan', 7, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Dexter', 7, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Floyd', 7, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Albany', 8, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Geneva', 8, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Olean', 8, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'White Plains', 8, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Rome', 8, 2)  
INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Troy', 8, 2)  


Step 2


Now, we have to create a WEB API to perform CRUD (Create, Replace, Update, and Delete) operations for employees. To create web API, open the visual studio 2019 >> file >> new >> project >> Select Web Application.


When you click the OK button, another window will appear on your screen for template selection where you have to select WebAPI and click on the OK button.


Step 3

Now, you have to go to solution explorer and right-click on Model folder >> Add >> New Item >> select Data from left panel >> Select ADO.NET Entity Data Model.


Now, click on the Add button and select the EF Designer from the database >> Next >> Gives your credential of SQL Server and select the database. Now, you have to click on the Add button and select your table and click on the finish button.




If you are a beginner or need any help to add an entity data model then you can read this article where I explained how to create an ADO.NET entity data model (EDM) in asp.net step by step.


Step 4

Now, we will add a new empty controller into our WEB API project to create a WEB API for perform CURD operation, and for that, you have to go to solution explorer and right-click on the Controllers folder >> Add >> Controller >> Select Web API 2 Controller-Empty >> Click on Add.


Now, you have to open our controller class and write the following APIs.

AngulerWebAppController.cs

using System;  
using System.Collections.Generic;  
using System.Data.Entity;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using AngulerWebApp.Models;  
 
namespace AngulerWebApp.Controllers  
{  
    [RoutePrefix("Api/Employee")]  
 public class AngulerWebAppController : ApiController  
    {  
        AngulerDBEntities objEntity = new AngulerDBEntities();  
 
        [HttpGet]  
        [Route("AllEmployeeDetails")]  
 public IHttpActionResult GetEmaployee()  
        {  
 try 
            {  
                var result = (from tblEmp in objEntity.tblEmployeeMasters  
                              join tblCountry in objEntity.CountryMasters on tblEmp.CountryId equals tblCountry.CountryId  
                              join tblState in objEntity.StateMasters on tblEmp.StateId equals tblState.StateId  
                              join tblCity in objEntity.CityMasters on tblEmp.Cityid equals tblCity.Cityid  
                              select new 
                              {  
                                  EmpId = tblEmp.EmpId,  
                                  FirstName = tblEmp.FirstName,  
                                  LastName = tblEmp.LastName,  
                                  DateofBirth = tblEmp.DateofBirth,  
                                  EmailId = tblEmp.EmailId,  
                                  Gender = tblEmp.Gender,  
                                  CountryId = tblEmp.CountryId,  
                                  StateId = tblEmp.StateId,  
                                  Cityid = tblEmp.Cityid,  
                                  Address = tblEmp.Address,  
                                  Pincode = tblEmp.Pincode,  
                                  Country = tblCountry.CountryName,  
                                  State = tblState.StateName,  
                                  City = tblCity.CityName  
                              }).ToList();  
 
 return Ok(result);  
            }  
 catch (Exception)  
            {  
 throw;  
            }  
        }  
 
        [HttpGet]  
        [Route("GetEmployeeDetailsById/{employeeId}")]  
 public IHttpActionResult GetEmaployeeById(string employeeId)  
        {  
 try 
            {  
                tblEmployeeMaster objEmp = new tblEmployeeMaster();  
 int ID = Convert.ToInt32(employeeId);  
 try 
                {  
                    objEmp = objEntity.tblEmployeeMasters.Find(ID);  
 if (objEmp == null)  
                    {  
 return NotFound();  
                    }  
                }  
 catch (Exception)  
                {  
 throw;  
                }  
 return Ok(objEmp);  
            }  
 catch (Exception ex)  
            {  
 throw ex;  
            }  
        }  
 
        [HttpPost]  
        [Route("InsertEmployeeDetails")]  
 public IHttpActionResult PostEmaployee(tblEmployeeMaster data)  
        {  
 try 
            {  
 if (!ModelState.IsValid)  
                {  
 return BadRequest(ModelState);  
                }  
 try 
                {  
                    data.DateofBirth = data.DateofBirth.HasValue ? data.DateofBirth.Value.AddDays(1) : (DateTime?)null;  
                    objEntity.tblEmployeeMasters.Add(data);  
                    objEntity.SaveChanges();  
                }  
 catch (Exception)  
                {  
 throw;  
                }  
 return Ok(data);  
            }  
 catch (Exception ex)  
            {  
 throw ex;  
            }  
        }  
 
        [HttpPut]  
        [Route("UpdateEmployeeDetails")]  
 public IHttpActionResult PutEmaployeeMaster(tblEmployeeMaster employee)  
        {  
 try 
            {  
 if (!ModelState.IsValid)  
 return BadRequest(ModelState);  
 
 try 
                {  
                    tblEmployeeMaster objEmp = new tblEmployeeMaster();  
                    objEmp = objEntity.tblEmployeeMasters.Find(employee.EmpId);  
 if (objEmp != null)  
                    {  
                        objEmp.FirstName = employee.FirstName;  
                        objEmp.LastName = employee.LastName;  
                        objEmp.Address = employee.Address;  
                        objEmp.EmailId = employee.EmailId;  
                        objEmp.DateofBirth = employee.DateofBirth.HasValue ? employee.DateofBirth.Value.AddDays(1) : (DateTime?)null;  
                        objEmp.Gender = employee.Gender;  
                        objEmp.CountryId = employee.CountryId;  
                        objEmp.StateId = employee.StateId;  
                        objEmp.Cityid = employee.Cityid;  
                        objEmp.Pincode = employee.Pincode;  
                    }  
 this.objEntity.SaveChanges();  
                }  
 catch (Exception)  
                {  
 throw;  
                }  
 return Ok(employee);  
            }  
 catch (Exception ex)  
            {  
 throw ex;  
            }  
        }  
        [HttpDelete]  
        [Route("DeleteEmployeeDetails")]  
 public IHttpActionResult DeleteEmaployeeDelete(int id)  
        {  
 try 
            {  
                tblEmployeeMaster emaployee = objEntity.tblEmployeeMasters.Find(id);  
 if (emaployee == null)  
                {  
 return NotFound();  
                }  
                objEntity.tblEmployeeMasters.Remove(emaployee);  
                objEntity.SaveChanges();  
 return Ok(emaployee);  
            }  
 catch (Exception ex)  
            {  
 
 throw ex;  
            }  
        }  
 
        [HttpGet]  
        [Route("Country")]  
 public IQueryable<CountryMaster> GetCountry()  
        {  
 try 
            {  
 return objEntity.CountryMasters;  
            }  
 catch (Exception)  
            {  
 throw;  
            }  
        }  
 public List<CountryMaster> CountryData()  
        {  
 try 
            {  
 return objEntity.CountryMasters.ToList();  
            }  
 catch (Exception ex)  
            {  
 throw ex;  
            }  
        }  
 
        [Route("Country/{CountryId}/State")]  
        [HttpGet]  
 public List<StateMaster> StateData(int CountryId)  
        {  
 try 
            {  
 return objEntity.StateMasters.Where(s => s.CountryId == CountryId).ToList();  
            }  
 catch (Exception ex)  
            {  
 
 throw ex;  
            }  
        }  
 
        [Route("State/{StateId}/City")]  
        [HttpGet]  
 public List<CityMaster> CityData(int StateId)  
        {  
 try 
            {  
 return objEntity.CityMasters.Where(s => s.StateId == StateId).ToList();  
            }  
 catch (Exception ex)  
            {  
 throw ex;  
            }  
        }  
 
        [HttpPost]  
        [Route("DeleteRecord")]  
 public IHttpActionResult DeleteRecord(List<tblEmployeeMaster> user)  
        {  
 string result = "";  
 if (!ModelState.IsValid)  
            {  
 return BadRequest(ModelState);  
            }  
 try 
            {  
                result = DeleteData(user);  
            }  
 catch (Exception ex)  
            {  
 throw;  
            }  
 return Ok(result);  
        }  
 private string DeleteData(List<tblEmployeeMaster> users)  
        {  
 string str = "";  
 try 
            {  
 foreach (var item in users)  
                {  
                    tblEmployeeMaster objEmp = new tblEmployeeMaster();  
                    objEmp.EmpId = item.EmpId;  
                    objEmp.FirstName = item.FirstName;  
                    objEmp.LastName = item.LastName;  
                    objEmp.Address = item.Address;  
                    objEmp.EmailId = item.EmailId;  
                    objEmp.DateofBirth = item.DateofBirth.HasValue ? item.DateofBirth.Value.AddDays(1) : (DateTime?)null;  
                    objEmp.Gender = item.Gender;  
                    objEmp.CountryId = item.CountryId;  
                    objEmp.StateId = item.StateId;  
                    objEmp.Cityid = item.Cityid;  
                    objEmp.Pincode = item.Pincode;  
                    var entry = objEntity.Entry(objEmp);  
 if (entry.State == EntityState.Detached) objEntity.tblEmployeeMasters.Attach(objEmp);  
                    objEntity.tblEmployeeMasters.Remove(objEmp);  
                }  
 int i = objEntity.SaveChanges();  
 if (i > 0)  
                {  
                    str = "Records has been deleted";  
                }  
 else 
                {  
                    str = "Records deletion has been faild";  
                }  
            }  
 catch (Exception ex)  
            {  
 throw ex;  
            }  
 return str;  
        }  
    }  
}  


Step 5

As you can see, we have created all the required API's and our API creation part is done, now we have to focus on the angular part, like installation of angular CLI, create a project of angular 11, consume API using angular 11, commands for build and run angular application and etc.


Now, first, we have to install angular CLI into our system, if you already installed angular CLI into your system then you can skip this step.


To, install angular CLI open package manager console or command prompt and type the below command and press enter.

npm install - g @angular/CLI  


NOTE

If you face any issue related to npm then you have to download and install the active LTS, or maintenance the LTS version of Node.js.

Now, we have to create a new angular project.

To create a new angular project open package manager console from API Project, write the following command, and hit enter.

ng new AngularCRUD  

Here, AngularCRUD is the name of our Angular project.



Now, when you open the project directory you can see the following project folder structure.


Now, we have to create a component into the created Angular project, for that first we have to change the directory and move to Angular project, So open the package manager console from your WEB API project and write the following command.

cd NameofYourAngulerProject  

Here, the Name of our angular project is AngularCRUD so you have to write the command as shown below and hit enter.

cd AngularCRUD  

Now, we will create a component, for that you have to write the following command and hit enter.

Create Component

ng g c employee  

Where an employee is the name of the component.


Step 6

Now, we will create a service and for that you have to write the following command and hit enter.

Create Service

ng g s employee  

Where the employee is the name of the service.


When you open the directory of your Angular project, you can see these two files are created in the directory as shown below.



Now, we will create a class in angular project same as model class, for that you have to write the following command.

Create a Class

ng g class employee   

Where the employee is the name of the class.


Now, we will write all the required properties of employees as shown below in the created class.

Class Employee

export class Employee {  
  EmpId: string;  
  FirstName: string;  
  LastName: string;  
  DateofBirth: Date;  
  EmailId: string;  
  Gender: string;  
  CountryId: string;  
  StateId: string;  
  Cityid: string;  
  Address: string;  
  Pincode: string;  
  Country: string;  
  State: string;  
  City: string;  
}  
 
export class Country {  
  CountryId: string;  
  CountryName: string;  
}  
 
export class State {  
  StateId: string;  
  StateName: string;  
  CountryId: string;  
}  
 
export class City {  
  Cityid: string;  
  CityName: string;  
  StateId: string;  
  CountryId: string;  
}  


Now, Open created an angular project in a new window of the visual studio by selecting the angular project folder, and open employee.service.ts, and import the necessary class and library as shown below.

import { Injectable } from '@angular/core';  
import { HttpClient } from '@angular/common/http';  
import { HttpHeaders } from '@angular/common/http';  
import { Observable } from 'rxjs';  
import { Employee, State,City } from './employee';  
import { Country } from './employee';  


Now, we will write all the required methods into employee.service.ts to consume the created WEB API.


@Injectable({  
  providedIn: 'root' 
})  
 
export class EmployeeService {  
  url = 'http://localhost:59465/Api/Employee';  
 
  constructor(private http: HttpClient) { }  
 
  getAllEmployee(): Observable<Employee[]> {  
 return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');  
  }  
 
  getEmployeeById(employeeId: string): Observable<Employee> {  
 return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);  
  }  
 
  createEmployee(employee: Employee): Observable<Employee> {  
 const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
 return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',  
      employee, httpOptions);  
  }  
 
  updateEmployee(employee: Employee): Observable<Employee> {  
 const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
 
 return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',  
      employee, httpOptions);  
  }  
 
  deleteEmployeeById(employeeid: string): Observable<number> {  
 const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
 return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' + employeeid,  
      httpOptions);  
  }  
 
  getCountry(): Observable<Country[]> {  
 return this.http.get<Country[]>(this.url + '/Country');  
  }  
 
  getState(CountryId: string): Observable<State[]> {  
 return this.http.get<State[]>(this.url + '/Country/' + CountryId + '/State');  
  }  
 
  getCity(StateId: string): Observable<City[]> {  
 return this.http.get<City[]>(this.url + '/State/' + StateId + '/City');  
  }  
 
  deleteData(user: Employee[]): Observable<string> {  
 const httpOptions = {  
      headers: new HttpHeaders({  
 'Content-Type': 'application/json' 
      })  
    };  
 return this.http.post<string>(this.url + '/DeleteRecord/', user, httpOptions);  
  }    
}  

As you can see in the code above, here we have taken variable URL and assign the URL or WEB API, where http://localhost:59465/ is the root URL taken from the property as shown below, and /Api/Employee is URL Prefix that we added while creating WEB API in Controller.



When you consume web API from any other port or domain, angular will block the particular URL and we called this issue CORS(Cross-Origin Resource Sharing). To resolve this issue you have to go into WEB API Project >> Goto NuGet Package Manager >> Download "CORS" in Web API project.


Now, you have to go to solution explorer >> App_Start folder of WEB API project >> WebApiConfig.cs class. In this file, you have to modify the register method and for that, you have to write the following code as shown below.

Add namespace

using System.Web.Http.Cors;  

Now, write following code in Register Method.

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



Continue.... Click Here



Source: C# Corner

0 comments