angular 11 basic


using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using AngularCustomerpoc.Models;


namespace AngularCustomerpoc.Controllers

{

    [Route("api/Customer")]

    [ApiController]

    public class TblcustomersController : ControllerBase

    {

        private readonly CustomerContext _context;


        public TblcustomersController(CustomerContext context)

        {

            _context = context;

        }


        // GET: api/Tblcustomers

        //[HttpGet]

        [HttpGet]

        [Route("CustomerDetails")]

        public async Task<ActionResult<IEnumerable<Tblcustomer>>> GetTblcustomers()

        {

            // return await _context.Tblcustomers.ToListAsync();




            return await _context.Tblcustomers.FromSqlRaw("EXEC SelectAllCustomers ").ToListAsync();



        }


        // GET: api/Tblcustomers/5

        //[HttpGet("{id}")]


        [HttpGet]  

        [Route("CustomerDetailsById/{id}")]

        public async Task<ActionResult<Tblcustomer>> GetTblcustomer(string id)

        {


            //var tblcustomer = await _context.Tblcustomers.FindAsync(id);

            var Tblcustomers = await _context.Tblcustomers.FromSqlRaw("EXEC [dbo].[Getbyid] {0}", id).ToListAsync();




            //if (tblcustomer == null)

            //{

            //    return NotFound();

            //}


            return Ok(Tblcustomers[0]);

            //return Ok(tblcustomer);

        }


        // PUT: api/Tblcustomers/5

        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754

        //[HttpPut("{id}")]


        [HttpPut]

        [Route("UpdateCustomerDetails/{id}")]

        public async Task<IActionResult> PutTblcustomer(string id, Tblcustomer tblcustomer)

        {

            if (id != tblcustomer.CustomerId)

            {

                return BadRequest();

            }


            _context.Entry(tblcustomer).State = EntityState.Modified;


            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateConcurrencyException)

            {

                if (!TblcustomerExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }


            return NoContent();

        }


        // POST: api/Tblcustomers

        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754

        //[HttpPost]

        [HttpPost]

        [Route("InsertCustomerDetails")]

        public async Task<ActionResult<Tblcustomer>> PostTblcustomer(Tblcustomer tblcustomer)

        {


            //var tblcustomers = await _context.Tblcustomers.FindAsync(tblcustomer.CustomerId);


            //if (tblcustomers != null)

            //{

            //    return tblcustomers;

            //}


            _context.Tblcustomers.Add(tblcustomer);

            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateException)

            {

                if (TblcustomerExists(tblcustomer.CustomerId))

                {

                    return Conflict();

                }

                else

                {

                    throw;

                }

            }


            return CreatedAtAction("GetTblcustomer", new { id = tblcustomer.CustomerId }, tblcustomer);

        }


        // DELETE: api/Tblcustomers/5

        //[HttpDelete("{id}")]

        [HttpDelete]

        //[Route("DeleteEmployeeDetails")]

        [Route("DeletCustomer")]

        public async Task<IActionResult> DeleteTblcustomer(string id)

        {

            var tblcustomer = await _context.Tblcustomers.FindAsync(id);

            if (tblcustomer == null)

            {

                return NotFound();

            }


            _context.Tblcustomers.Remove(tblcustomer);

            await _context.SaveChangesAsync();


            return NoContent();

        }


        private bool TblcustomerExists(string id)

        {

            return _context.Tblcustomers.Any(e => e.CustomerId == id);

        }

    }

}





angular 11 basic

In this article, I am going to explain how to perform simple CRUD 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.
 
I have also written an article about the Angular 12 CRUD Exmple with using WEB API that you might like to read. Here, I have also explained a way to update the older version of angular with the latest version of angular, So you can keep your angular application upto date as well as also explained the way to update the latest version of angular material as well as the change of angular material. I not posting the same article again on the c# corner platform to avoid duplicate articles, so you can read it from my blog codingvila.com. 

Angular 11 CURD Application using Web API With Material Design
 
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 CRUD operation using Angular 11 and WEB API.
  2. Use Angular Material theme and use maximum angular material controls to implement CRUD 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 CRUD 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
  1. CREATE TABLE [dbo].[tblEmployeeMaster] (  
  2. [EmpId] INT IDENTITY (1, 1) NOT NULL,  
  3. [FirstName] VARCHAR (50) NULL,  
  4. [LastName] VARCHAR (50) NULL,  
  5. [DateofBirth] DATETIME NULL,  
  6. [EmailId] NVARCHAR (50) NULL,  
  7. [Gender] NCHAR (10) NULL,  
  8. [CountryId] INT NULL,  
  9. [StateId] INT NULL,  
  10. [Cityid] INT NULL,  
  11. [Address] VARCHAR (100) NULL,  
  12. [Pincode] VARCHAR (50) NULL,  
  13. CONSTRAINT [PK_tblEmployeeMaster] PRIMARY KEY CLUSTERED ([EmpId] ASC)  
  14. );  
Country
  1. CREATE TABLE [dbo].[CountryMaster] (  
  2. [CountryId] INT IDENTITY (1, 1) NOT NULL,  
  3. [CountryName] VARCHAR (50) NULL,  
  4. CONSTRAINT [PK_CountryMaster] PRIMARY KEY CLUSTERED ([CountryId] ASC)  
  5. );  
State
  1. CREATE TABLE [dbo].[StateMaster] (  
  2. [StateId] INT IDENTITY (1, 1) NOT NULL,  
  3. [StateName] VARCHAR (50) NULL,  
  4. [CountryId] INT NOT NULL,  
  5. CONSTRAINT [PK_StateMaster] PRIMARY KEY CLUSTERED ([StateId] ASC)  
  6. );  
City
  1. CREATE TABLE [dbo].[CityMaster] (  
  2. [Cityid] INT IDENTITY (1, 1) NOT NULL,  
  3. [CityName] VARCHAR (50) NULL,  
  4. [StateId] INT NOT NULL,  
  5. [CountryId] INT NOT NULL,  
  6. CONSTRAINT [PK_CityMaster] PRIMARY KEY CLUSTERED ([Cityid] ASC)  
  7. );  
Now, Please add a few sample records into the country, state, and city table for demonstration.
  1. INSERT [dbo].[CountryMaster] ([CountryName]) VALUES (N'India')    
  2. INSERT [dbo].[CountryMaster] ([CountryName]) VALUES (N'United States')   
  1. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Andhra Pradesh', 1)    
  2. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Gujarat', 1)    
  3. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Kerala', 1)    
  4. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Alabama', 2)    
  5. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Hawaii', 2)    
  6. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Texas', 2)    
  7. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'New Mexico', 2)    
  8. INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'New York', 2)   
  1. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Visakhapatnam', 1, 1)  
  2. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vijayawada', 1, 1)  
  3. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Guntur', 1, 1)  
  4. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Nellore', 1, 1)  
  5. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kurnool', 1, 1)  
  6. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Ahmedabad', 2, 1)  
  7. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Surat', 2, 1)  
  8. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vadodara', 2, 1)  
  9. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Rajkot', 2, 1)  
  10. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Bhavnagar', 2, 1)  
  11. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Jamnagar', 2, 1)  
  12. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Junagadh', 2, 1)  
  13. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Thiruvananthapuram', 3, 1)  
  14. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kochi', 3, 1)  
  15. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kozhikode', 3, 1)  
  16. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kollam', 3, 1)  
  17. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kannur', 3, 1)  
  18. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Malappuram', 3, 1)  
  19. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vatakara', 3, 1)  
  20. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Adamsville', 4, 2)  
  21. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Addison', 4, 2)  
  22. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Allgood', 4, 2)  
  23. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Auburn', 4, 2)  
  24. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Honolulu', 5, 2)  
  25. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'East Honolulu', 5, 2)  
  26. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kahului', 5, 2)  
  27. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Abernathy', 6, 2)  
  28. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Alton', 6, 2)  
  29. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Barstow', 6, 2)  
  30. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Bellmead', 6, 2)  
  31. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Angel Fire', 7, 2)  
  32. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Capitan', 7, 2)  
  33. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Dexter', 7, 2)  
  34. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Floyd', 7, 2)  
  35. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Albany', 8, 2)  
  36. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Geneva', 8, 2)  
  37. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Olean', 8, 2)  
  38. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'White Plains', 8, 2)  
  39. INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Rome', 8, 2)  
  40. 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.
 
ADO.NET entity data model
 
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 CRUD 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
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Web.Http;  
  8. using AngulerWebApp.Models;  
  9.    
  10. namespace AngulerWebApp.Controllers  
  11. {  
  12.     [RoutePrefix("Api/Employee")]  
  13.     public class AngulerWebAppController : ApiController  
  14.     {  
  15.         AngulerDBEntities objEntity = new AngulerDBEntities();  
  16.    
  17.         [HttpGet]  
  18.         [Route("AllEmployeeDetails")]  
  19.         public IHttpActionResult GetEmaployee()  
  20.         {  
  21.             try  
  22.             {  
  23.                 var result = (from tblEmp in objEntity.tblEmployeeMasters  
  24.                               join tblCountry in objEntity.CountryMasters on tblEmp.CountryId equals tblCountry.CountryId  
  25.                               join tblState in objEntity.StateMasters on tblEmp.StateId equals tblState.StateId  
  26.                               join tblCity in objEntity.CityMasters on tblEmp.Cityid equals tblCity.Cityid  
  27.                               select new  
  28.                               {  
  29.                                   EmpId = tblEmp.EmpId,  
  30.                                   FirstName = tblEmp.FirstName,  
  31.                                   LastName = tblEmp.LastName,  
  32.                                   DateofBirth = tblEmp.DateofBirth,  
  33.                                   EmailId = tblEmp.EmailId,  
  34.                                   Gender = tblEmp.Gender,  
  35.                                   CountryId = tblEmp.CountryId,  
  36.                                   StateId = tblEmp.StateId,  
  37.                                   Cityid = tblEmp.Cityid,  
  38.                                   Address = tblEmp.Address,  
  39.                                   Pincode = tblEmp.Pincode,  
  40.                                   Country = tblCountry.CountryName,  
  41.                                   State = tblState.StateName,  
  42.                                   City = tblCity.CityName  
  43.                               }).ToList();  
  44.    
  45.                 return Ok(result);  
  46.             }  
  47.             catch (Exception)  
  48.             {  
  49.                 throw;  
  50.             }  
  51.         }  
  52.    
  53.         [HttpGet]  
  54.         [Route("GetEmployeeDetailsById/{employeeId}")]  
  55.         public IHttpActionResult GetEmaployeeById(string employeeId)  
  56.         {  
  57.             try  
  58.             {  
  59.                 tblEmployeeMaster objEmp = new tblEmployeeMaster();  
  60.                 int ID = Convert.ToInt32(employeeId);  
  61.                 try  
  62.                 {  
  63.                     objEmp = objEntity.tblEmployeeMasters.Find(ID);  
  64.                     if (objEmp == null)  
  65.                     {  
  66.                         return NotFound();  
  67.                     }  
  68.                 }  
  69.                 catch (Exception)  
  70.                 {  
  71.                     throw;  
  72.                 }  
  73.                 return Ok(objEmp);  
  74.             }  
  75.             catch (Exception ex)  
  76.             {  
  77.                 throw ex;  
  78.             }  
  79.         }  
  80.    
  81.         [HttpPost]  
  82.         [Route("InsertEmployeeDetails")]  
  83.         public IHttpActionResult PostEmaployee(tblEmployeeMaster data)  
  84.         {  
  85.             try  
  86.             {  
  87.                 if (!ModelState.IsValid)  
  88.                 {  
  89.                     return BadRequest(ModelState);  
  90.                 }  
  91.                 try  
  92.                 {  
  93.                     data.DateofBirth = data.DateofBirth.HasValue ? data.DateofBirth.Value.AddDays(1) : (DateTime?)null;  
  94.                     objEntity.tblEmployeeMasters.Add(data);  
  95.                     objEntity.SaveChanges();  
  96.                 }  
  97.                 catch (Exception)  
  98.                 {  
  99.                     throw;  
  100.                 }  
  101.                 return Ok(data);  
  102.             }  
  103.             catch (Exception ex)  
  104.             {  
  105.                 throw ex;  
  106.             }  
  107.         }  
  108.    
  109.         [HttpPut]  
  110.         [Route("UpdateEmployeeDetails")]  
  111.         public IHttpActionResult PutEmaployeeMaster(tblEmployeeMaster employee)  
  112.         {  
  113.             try  
  114.             {  
  115.                 if (!ModelState.IsValid)  
  116.                     return BadRequest(ModelState);  
  117.    
  118.                 try  
  119.                 {  
  120.                     tblEmployeeMaster objEmp = new tblEmployeeMaster();  
  121.                     objEmp = objEntity.tblEmployeeMasters.Find(employee.EmpId);  
  122.                     if (objEmp != null)  
  123.                     {  
  124.                         objEmp.FirstName = employee.FirstName;  
  125.                         objEmp.LastName = employee.LastName;  
  126.                         objEmp.Address = employee.Address;  
  127.                         objEmp.EmailId = employee.EmailId;  
  128.                         objEmp.DateofBirth = employee.DateofBirth.HasValue ? employee.DateofBirth.Value.AddDays(1) : (DateTime?)null;  
  129.                         objEmp.Gender = employee.Gender;  
  130.                         objEmp.CountryId = employee.CountryId;  
  131.                         objEmp.StateId = employee.StateId;  
  132.                         objEmp.Cityid = employee.Cityid;  
  133.                         objEmp.Pincode = employee.Pincode;  
  134.                     }  
  135.                     this.objEntity.SaveChanges();  
  136.                 }  
  137.                 catch (Exception)  
  138.                 {  
  139.                     throw;  
  140.                 }  
  141.                 return Ok(employee);  
  142.             }  
  143.             catch (Exception ex)  
  144.             {  
  145.                 throw ex;  
  146.             }  
  147.         }  
  148.         [HttpDelete]  
  149.         [Route("DeleteEmployeeDetails")]  
  150.         public IHttpActionResult DeleteEmaployeeDelete(int id)  
  151.         {  
  152.             try  
  153.             {  
  154.                 tblEmployeeMaster emaployee = objEntity.tblEmployeeMasters.Find(id);  
  155.                 if (emaployee == null)  
  156.                 {  
  157.                     return NotFound();  
  158.                 }  
  159.                 objEntity.tblEmployeeMasters.Remove(emaployee);  
  160.                 objEntity.SaveChanges();  
  161.                 return Ok(emaployee);  
  162.             }  
  163.             catch (Exception ex)  
  164.             {  
  165.    
  166.                 throw ex;  
  167.             }  
  168.         }  
  169.    
  170.         [HttpGet]  
  171.         [Route("Country")]  
  172.         public IQueryable<CountryMaster> GetCountry()  
  173.         {  
  174.             try  
  175.             {  
  176.                 return objEntity.CountryMasters;  
  177.             }  
  178.             catch (Exception)  
  179.             {  
  180.                 throw;  
  181.             }  
  182.         }  
  183.         public List<CountryMaster> CountryData()  
  184.         {  
  185.             try  
  186.             {  
  187.                 return objEntity.CountryMasters.ToList();  
  188.             }  
  189.             catch (Exception ex)  
  190.             {  
  191.                 throw ex;  
  192.             }  
  193.         }  
  194.    
  195.         [Route("Country/{CountryId}/State")]  
  196.         [HttpGet]  
  197.         public List<StateMaster> StateData(int CountryId)  
  198.         {  
  199.             try  
  200.             {  
  201.                 return objEntity.StateMasters.Where(s => s.CountryId == CountryId).ToList();  
  202.             }  
  203.             catch (Exception ex)  
  204.             {  
  205.    
  206.                 throw ex;  
  207.             }  
  208.         }  
  209.    
  210.         [Route("State/{StateId}/City")]  
  211.         [HttpGet]  
  212.         public List<CityMaster> CityData(int StateId)  
  213.         {  
  214.             try  
  215.             {  
  216.                 return objEntity.CityMasters.Where(s => s.StateId == StateId).ToList();  
  217.             }  
  218.             catch (Exception ex)  
  219.             {  
  220.                 throw ex;  
  221.             }  
  222.         }  
  223.    
  224.         [HttpPost]  
  225.         [Route("DeleteRecord")]  
  226.         public IHttpActionResult DeleteRecord(List<tblEmployeeMaster> user)  
  227.         {  
  228.             string result = "";  
  229.             if (!ModelState.IsValid)  
  230.             {  
  231.                 return BadRequest(ModelState);  
  232.             }  
  233.             try  
  234.             {  
  235.                 result = DeleteData(user);  
  236.             }  
  237.             catch (Exception ex)  
  238.             {  
  239.                 throw;  
  240.             }  
  241.             return Ok(result);  
  242.         }  
  243.         private string DeleteData(List<tblEmployeeMaster> users)  
  244.         {  
  245.             string str = "";  
  246.             try  
  247.             {  
  248.                 foreach (var item in users)  
  249.                 {  
  250.                     tblEmployeeMaster objEmp = new tblEmployeeMaster();  
  251.                     objEmp.EmpId = item.EmpId;  
  252.                     objEmp.FirstName = item.FirstName;  
  253.                     objEmp.LastName = item.LastName;  
  254.                     objEmp.Address = item.Address;  
  255.                     objEmp.EmailId = item.EmailId;  
  256.                     objEmp.DateofBirth = item.DateofBirth.HasValue ? item.DateofBirth.Value.AddDays(1) : (DateTime?)null;  
  257.                     objEmp.Gender = item.Gender;  
  258.                     objEmp.CountryId = item.CountryId;  
  259.                     objEmp.StateId = item.StateId;  
  260.                     objEmp.Cityid = item.Cityid;  
  261.                     objEmp.Pincode = item.Pincode;  
  262.                     var entry = objEntity.Entry(objEmp);  
  263.                     if (entry.State == EntityState.Detached) objEntity.tblEmployeeMasters.Attach(objEmp);  
  264.                     objEntity.tblEmployeeMasters.Remove(objEmp);  
  265.                 }  
  266.                 int i = objEntity.SaveChanges();  
  267.                 if (i > 0)  
  268.                 {  
  269.                     str = "Records has been deleted";  
  270.                 }  
  271.                 else  
  272.                 {  
  273.                     str = "Records deletion has been faild";  
  274.                 }  
  275.             }  
  276.             catch (Exception ex)  
  277.             {  
  278.                 throw ex;  
  279.             }  
  280.             return str;  
  281.         }  
  282.     }  
  283. }  
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.
  1. 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.
  1. 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.
 
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.
  1. cd NameofYourAngulerProject  
Here, the Name of our angular project is AngularCRUD so you have to write the command as shown below and hit enter.
  1. cd AngularCRUD  
Now, we will create a component, for that you have to write the following command and hit enter.
 
Create Component
  1. 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
  1. 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.
 
Angular Component and Service
 
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
  1. 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
  1. export class Employee {  
  2.   EmpId: string;  
  3.   FirstName: string;  
  4.   LastName: string;  
  5.   DateofBirth: Date;  
  6.   EmailId: string;  
  7.   Gender: string;  
  8.   CountryId: string;  
  9.   StateId: string;  
  10.   Cityid: string;  
  11.   Address: string;  
  12.   Pincode: string;  
  13.   Country: string;  
  14.   State: string;  
  15.   City: string;  
  16. }  
  17.   
  18. export class Country {  
  19.   CountryId: string;  
  20.   CountryName: string;  
  21. }  
  22.   
  23. export class State {  
  24.   StateId: string;  
  25.   StateName: string;  
  26.   CountryId: string;  
  27. }  
  28.   
  29. export class City {  
  30.   Cityid: string;  
  31.   CityName: string;  
  32.   StateId: string;  
  33.   CountryId: string;  
  34. }  
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.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { HttpHeaders } from '@angular/common/http';  
  4. import { Observable } from 'rxjs';  
  5. import { Employee, State,City } from './employee';  
  6. import { Country } from './employee';  
Now, we will write all the required methods into employee.service.ts to consume the created WEB API.
  1. @Injectable({  
  2.   providedIn: 'root'  
  3. })  
  4.    
  5. export class EmployeeService {  
  6.   url = 'http://localhost:59465/Api/Employee';  
  7.    
  8.   constructor(private http: HttpClient) { }  
  9.    
  10.   getAllEmployee(): Observable<Employee[]> {  
  11.     return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');  
  12.   }  
  13.    
  14.   getEmployeeById(employeeId: string): Observable<Employee> {  
  15.     return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);  
  16.   }  
  17.    
  18.   createEmployee(employee: Employee): Observable<Employee> {  
  19.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  20.     return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',  
  21.       employee, httpOptions);  
  22.   }  
  23.    
  24.   updateEmployee(employee: Employee): Observable<Employee> {  
  25.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  26.    
  27.     return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',  
  28.       employee, httpOptions);  
  29.   }  
  30.    
  31.   deleteEmployeeById(employeeid: string): Observable<number> {  
  32.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  33.     return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' + employeeid,  
  34.       httpOptions);  
  35.   }  
  36.    
  37.   getCountry(): Observable<Country[]> {  
  38.     return this.http.get<Country[]>(this.url + '/Country');  
  39.   }  
  40.    
  41.   getState(CountryId: string): Observable<State[]> {  
  42.     return this.http.get<State[]>(this.url + '/Country/' + CountryId + '/State');  
  43.   }  
  44.    
  45.   getCity(StateId: string): Observable<City[]> {  
  46.     return this.http.get<City[]>(this.url + '/State/' + StateId + '/City');  
  47.   }  
  48.    
  49.   deleteData(user: Employee[]): Observable<string> {  
  50.     const httpOptions = {  
  51.       headers: new HttpHeaders({  
  52.         'Content-Type''application/json'  
  53.       })  
  54.     };  
  55.     return this.http.post<string>(this.url + '/DeleteRecord/', user, httpOptions);  
  56.   }    
  57. }  
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.
 
URL Properties
 
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.
 
Cross Origin Resource Sharing
 
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
  1. using System.Web.Http.Cors;  
Now, write following code in Register Method.
  1. var cors = new EnableCorsAttribute("*""*""*");//origins,headers,methods  
  2. config.EnableCors(cors);  
Step 7
 
Now, we have to install an Angular Material theme So, open the package manager console and write the following code.
  1. npm install --save @angular/material @angular/cdk @angular/animations  
You can check the package.json file in the Angular project to verify the Material theme is installed or not.
 
package.json
  1. {  
  2.   "name""angular-crud",  
  3.   "version""0.0.0",  
  4.   "scripts": {  
  5.     "ng""ng",  
  6.     "start""ng serve",  
  7.     "build""ng build",  
  8.     "test""ng test",  
  9.     "lint""ng lint",  
  10.     "e2e""ng e2e"  
  11.   },  
  12.   "private"true,  
  13.   "dependencies": {  
  14.     "@angular/animations""^11.0.2",  
  15.     "@angular/cdk""^11.0.1",  
  16.     "@angular/common""~11.0.1",  
  17.     "@angular/compiler""~11.0.1",  
  18.     "@angular/core""~11.0.1",  
  19.     "@angular/forms""~11.0.1",  
  20.     "@angular/material""^11.0.1",  
  21.     "@angular/platform-browser""~11.0.1",  
  22.     "@angular/platform-browser-dynamic""~11.0.1",  
  23.     "@angular/router""~11.0.1",  
  24.     "rxjs""~6.6.0",  
  25.     "tslib""^2.0.0",  
  26.     "zone.js""~0.10.2"  
  27.   },  
  28.   "devDependencies": {  
  29.     "@angular-devkit/build-angular""~0.1100.2",  
  30.     "@angular/cli""^11.0.2",  
  31.     "@angular/compiler-cli""~11.0.1",  
  32.     "@types/jasmine""~3.6.0",  
  33.     "@types/node""^12.11.1",  
  34.     "codelyzer""^6.0.0",  
  35.     "jasmine-core""~3.6.0",  
  36.     "jasmine-spec-reporter""~5.0.0",  
  37.     "karma""~5.1.0",  
  38.     "karma-chrome-launcher""~3.1.0",  
  39.     "karma-coverage""~2.0.3",  
  40.     "karma-jasmine""~4.0.0",  
  41.     "karma-jasmine-html-reporter""^1.5.0",  
  42.     "protractor""~7.0.0",  
  43.     "ts-node""~8.3.0",  
  44.     "tslint""~6.1.0",  
  45.     "typescript""~4.0.2"  
  46.   }  
  47. }  
Now, you have to import all the required libraries in app.module.ts as shown below.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { EmployeeService } from './employee.service';  
  4. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  5. import { HttpClientModule, HttpClient } from '@angular/common/http';  
  6. import { MatInputModule } from "@angular/material/input";  
  7. import { MatCardModule } from '@angular/material/card';  
  8. import { MatButtonModule } from '@angular/material/button';  
  9. import { MatDatepickerModule } from '@angular/material/datepicker';  
  10. import { MatMenuModule } from '@angular/material/menu';  
  11. import { MatNativeDateModule } from '@angular/material/core';  
  12. import { MatIconModule } from '@angular/material/icon';  
  13. import { MatSidenavModule } from '@angular/material/sidenav';  
  14. import { MatFormFieldModule } from '@angular/material/form-field';  
  15. import { MatTooltipModule } from '@angular/material/tooltip';  
  16. import { MatToolbarModule } from '@angular/material/toolbar';  
  17. import { MatRadioModule } from '@angular/material/radio';  
  18. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  19. import { AppRoutingModule } from './app-routing.module';  
  20. import { AppComponent } from './app.component';  
  21. import { EmployeeComponent } from './employee/employee.component';  
  22. import { MatCheckboxModule } from '@angular/material/checkbox';  
  23. import { MatSelectModule } from '@angular/material/select';  
  24. import { MatSnackBarModule } from '@angular/material/snack-bar';  
  25. import { MatTableModule } from '@angular/material/table';  
  26. import { CdkTableModule } from '@angular/cdk/table';  
  27. import { MatPaginatorModule } from '@angular/material/paginator';  
  28.   
  29. @NgModule({  
  30.   declarations: [  
  31.     AppComponent,  
  32.     EmployeeComponent  
  33.   ],  
  34.   imports: [  
  35.     BrowserModule,  
  36.     FormsModule,  
  37.     ReactiveFormsModule,  
  38.     HttpClientModule,  
  39.     BrowserAnimationsModule,  
  40.     MatButtonModule,  
  41.     MatMenuModule,  
  42.     MatDatepickerModule,  
  43.     MatNativeDateModule,  
  44.     MatIconModule,  
  45.     MatRadioModule,  
  46.     MatCardModule,  
  47.     MatSidenavModule,  
  48.     MatFormFieldModule,  
  49.     MatInputModule,  
  50.     MatTooltipModule,  
  51.     MatToolbarModule,  
  52.     AppRoutingModule,  
  53.     MatCheckboxModule,  
  54.     MatSelectModule,  
  55.     MatSnackBarModule,  
  56.     MatTableModule,  
  57.     CdkTableModule,  
  58.     MatPaginatorModule  
  59.   ],  
  60.   providers: [],  
  61.   bootstrap: [AppComponent]  
  62. })  
  63.   
  64. export class AppModule { }  
Now, you have to import CSS of the angular material theme in the styles.css file as shown below.
  1. @import '@angular/material/prebuilt-themes/indigo-pink.css';  
Step 8
 
Now, you have to write the following HTML code in the employee.component.html file.
 
employee.component.html
  1. <div class="container">    
  2.   <mat-card class="mat-elevation-z8">    
  3.     <mat-toolbar color="accent" style="box-shadow: 0 3px 5px -1px rgba(0,0,0,.2), 0 6px 10px 0 rgba(0,0,0,.14), 0 1px 18px 0 rgba(0,0,0,.12);">    
  4.       <div align="center" style="color:white;text-align: right;">    
  5.         Codingvila | Angular 11 Application using Web API With Material Design    
  6.       </div>    
  7.     </mat-toolbar>    
  8.     <br><br>    
  9.     <mat-card-content>    
  10.       <form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit()">    
  11.         <table>    
  12.           <tr>    
  13.             <td class="tbl1">    
  14.               <mat-form-field class="demo-full-width">    
  15.                 <input formControlName="FirstName" matTooltip="Enter Employee FirstName" matInput placeholder="FirstName" autocomplete="off">    
  16.               </mat-form-field>    
  17.               <mat-error>    
  18.                 <span *ngIf="!employeeForm.get('FirstName').value && employeeForm.get('FirstName').touched"></span>    
  19.               </mat-error>    
  20.             </td>    
  21.             <td class="tbl1">    
  22.               <mat-form-field class="demo-full-width">    
  23.                 <input formControlName="LastName" matTooltip="Enter Employee LastName" matInput placeholder="LastName" autocomplete="off">    
  24.               </mat-form-field>    
  25.               <mat-error>    
  26.                 <span *ngIf="!employeeForm.get('LastName').value && employeeForm.get('LastName').touched"></span>    
  27.               </mat-error>    
  28.             </td>    
  29.             <td class="tbl1">    
  30.               <mat-form-field class="demo-full-width">    
  31.                 <input matInput [matDatepicker]="picker" matTooltip="Enter Date Of Birth" formControlName="DateofBirth" placeholder="Date Of Birth" autocomplete="off">    
  32.                 <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>    
  33.                 <mat-datepicker #picker></mat-datepicker>    
  34.               </mat-form-field>    
  35.               <mat-error>    
  36.                 <span *ngIf="!employeeForm.get('DateofBirth').value && employeeForm.get('DateofBirth').touched"></span>    
  37.               </mat-error>    
  38.             </td>    
  39.             <td class="tbl1">    
  40.               <mat-form-field class="demo-full-width">    
  41.                 <input formControlName="EmailId" matTooltip="Enter EmailId" matInput placeholder="Email ID" autocomplete="off">    
  42.               </mat-form-field>    
  43.               <mat-error>    
  44.                 <span *ngIf="!employeeForm.get('EmailId').value && employeeForm.get('EmailId').touched"></span>    
  45.               </mat-error>    
  46.             </td>    
  47.             <td class="tbl1">    
  48.               <span>Gender</span>     
  49.      
  50.               <mat-radio-group matTooltip="Enter Gender" formControlName="Gender">    
  51.                 <mat-radio-button value="0" [checked]="isMale">Male</mat-radio-button>      
  52.                 <mat-radio-button value="1" [checked]="isFeMale">Female</mat-radio-button>      
  53.               </mat-radio-group>    
  54.               <mat-error>    
  55.                 <span *ngIf="!employeeForm.get('Gender').value && employeeForm.get('Gender').touched"></span>    
  56.               </mat-error>    
  57.             </td>    
  58.           </tr>    
  59.           <tr>    
  60.             <td class="tbl1">    
  61.               <mat-form-field>    
  62.                 <mat-label>Country</mat-label>    
  63.                 <mat-select (selectionChange)="FillStateDDL($event)" formControlName="Country" matTooltip="Select Country" autocomplete="off">    
  64.                   <mat-option *ngFor="let Country of (allCountry | async)" [value]="Country.CountryId">    
  65.                     {{Country.CountryName}}    
  66.                   </mat-option>    
  67.                 </mat-select>    
  68.               </mat-form-field>    
  69.             </td>    
  70.             <td class="tbl1">    
  71.               <mat-form-field>    
  72.                 <mat-label>State</mat-label>    
  73.                 <mat-select (selectionChange)="FillCityDDL($event)" formControlName="State" matTooltip="Select State" autocomplete="off">    
  74.                   <mat-option *ngFor="let State of (allState | async)" [value]="State.StateId">    
  75.                     {{State.StateName}}    
  76.                   </mat-option>    
  77.                 </mat-select>    
  78.               </mat-form-field>    
  79.             </td>    
  80.             <td class="tbl1">    
  81.               <mat-form-field>    
  82.                 <mat-label>City</mat-label>    
  83.                 <mat-select formControlName="City" (selectionChange)="GetSelectedCity($event)" matTooltip="Select City" autocomplete="off">    
  84.                   <mat-option *ngFor="let City of (allCity | async)" [value]="City.Cityid">    
  85.                     {{City.CityName}}    
  86.                   </mat-option>    
  87.                 </mat-select>    
  88.               </mat-form-field>    
  89.             </td>    
  90.             <td class="tbl1">    
  91.               <mat-form-field class="demo-full-width">    
  92.                 <input matTooltip="Enter Address" formControlName="Address" matInput placeholder="Address" autocomplete="off">    
  93.               </mat-form-field>    
  94.               <mat-error>    
  95.                 <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>    
  96.               </mat-error>    
  97.             </td>    
  98.             <td class="tbl1">    
  99.               <mat-form-field class="demo-full-width">    
  100.                 <input formControlName="Pincode" matTooltip="Enter Pine Code" matInput placeholder="Pincode" minLength="5" maxLength="6" autocomplete="off">    
  101.               </mat-form-field>    
  102.               <mat-error>    
  103.                 <span *ngIf="!employeeForm.get('Pincode').value && employeeForm.get('Pincode').touched"></span>    
  104.               </mat-error>    
  105.             </td>    
  106.           </tr>    
  107.           <tr>    
  108.             <td class="content-center">    
  109.               <button type="submit" mat-raised-button color="accent" matTooltip="Submit" [disabled]="!employeeForm.valid">Submit</button>        
  110.               <button type="reset" mat-raised-button color="accent" matTooltip="Reset" (click)="resetForm()">Reset</button>    
  111.             </td>    
  112.             <td>    
  113.               <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">    
  114.                 {{massage}}    
  115.               </p>    
  116.             </td>    
  117.             <td></td>    
  118.             <td></td>    
  119.           </tr>    
  120.         </table>    
  121.         <br><br>    
  122.      
  123.         <mat-form-field>    
  124.           <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">    
  125.         </mat-form-field>    
  126.                 
  127.         <button mat-icon-button aria-label="Example icon button with a delete icon" type="button" mat-raised-button color="accent" matTooltip="Delete" (click)="DeleteData()"><mat-icon>delete</mat-icon></button>    
  128.      
  129.         <div>    
  130.      
  131.           <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8" style="box-shadow: 0 3px 5px -1px rgba(0,0,0,.2), 0 6px 10px 0 rgba(0,0,0,.14), 0 1px 18px 0 rgba(0,0,0,.12);">    
  132.      
  133.             <!-- Checkbox Column -->    
  134.             <ng-container matColumnDef="select">    
  135.               <th style="width: 100px;" mat-header-cell *matHeaderCellDef>    
  136.                 <mat-checkbox (change)="$event ? masterToggle() : null"    
  137.                               [checked]="selection.hasValue() && isAllSelected()"    
  138.                               [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>    
  139.               </th>    
  140.               <td mat-cell *matCellDef="let row">    
  141.                 <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null"    
  142.                               [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)"></mat-checkbox>    
  143.               </td>    
  144.             </ng-container>    
  145.      
  146.             <ng-container matColumnDef="FirstName">    
  147.               <th mat-header-cell *matHeaderCellDef mat-sort-header> First Name </th>    
  148.               <td mat-cell *matCellDef="let employee"> {{employee.FirstName}} </td>    
  149.             </ng-container>    
  150.      
  151.             <ng-container matColumnDef="LastName">    
  152.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Last Name </th>    
  153.               <td mat-cell *matCellDef="let employee"> {{employee.LastName}} </td>    
  154.             </ng-container>    
  155.      
  156.             <ng-container matColumnDef="DateofBirth">    
  157.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Date Of Birth </th>    
  158.               <td mat-cell *matCellDef="let employee"> {{employee.DateofBirth | date:'dd-MM-yyyy'}}</td>    
  159.             </ng-container>    
  160.      
  161.             <ng-container matColumnDef="EmailId">    
  162.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Email Id </th>    
  163.               <td mat-cell *matCellDef="let employee"> {{employee.EmailId}} </td>    
  164.             </ng-container>    
  165.      
  166.             <ng-container matColumnDef="Gender">    
  167.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Gender </th>    
  168.               <td mat-cell *matCellDef="let employee"> {{employee.Gender ==0? 'Male' : 'Female'}} </td>    
  169.             </ng-container>    
  170.      
  171.             <ng-container matColumnDef="Country">    
  172.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Country </th>    
  173.               <td mat-cell *matCellDef="let employee"> {{employee.Country}} </td>    
  174.             </ng-container>    
  175.      
  176.             <ng-container matColumnDef="State">    
  177.               <th mat-header-cell *matHeaderCellDef mat-sort-header> State </th>    
  178.               <td mat-cell *matCellDef="let employee"> {{employee.State}} </td>    
  179.             </ng-container>    
  180.      
  181.             <ng-container matColumnDef="City">    
  182.               <th mat-header-cell *matHeaderCellDef mat-sort-header> City </th>    
  183.               <td mat-cell *matCellDef="let employee"> {{employee.City}} </td>    
  184.             </ng-container>    
  185.      
  186.             <ng-container matColumnDef="Address">    
  187.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Address </th>    
  188.               <td mat-cell *matCellDef="let employee"> {{employee.Address}} </td>    
  189.             </ng-container>    
  190.      
  191.             <ng-container matColumnDef="Pincode">    
  192.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Pincode </th>    
  193.               <td mat-cell *matCellDef="let employee"> {{employee.Pincode}} </td>    
  194.             </ng-container>    
  195.      
  196.             <ng-container matColumnDef="Edit">    
  197.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Edit </th>    
  198.      
  199.               <td mat-cell *matCellDef="let employee">    
  200.      
  201.                 <button mat-icon-button aria-label="Example icon button with a vertical three dot icon" type="button" mat-raised-button color="accent" matTooltip="Edit" (click)="loadEmployeeToEdit(employee.EmpId)"><mat-icon>edit</mat-icon></button>    
  202.      
  203.               </td>    
  204.             </ng-container>    
  205.      
  206.             <ng-container matColumnDef="Delete">    
  207.               <th mat-header-cell *matHeaderCellDef mat-sort-header> Delete </th>    
  208.               <td mat-cell *matCellDef="let employee"> <button mat-icon-button aria-label="Example icon button with a delete icon" type="button" mat-raised-button color="accent" matTooltip="Delete" (click)="deleteEmployee(employee.EmpId)"><mat-icon>delete_forever</mat-icon></button></td>    
  209.             </ng-container>    
  210.      
  211.             <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>    
  212.             <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>    
  213.           </table>    
  214.      
  215.           <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>    
  216.         </div>    
  217.      
  218.       </form>    
  219.     </mat-card-content>    
  220.   </mat-card>    
  221. </div>     
Step 9
 
Now, you have to write the following code into the app.component.html file.
 
app.component.html
  1. <p>  
  2. <app-employee></app-employee>  
  3. </p>  
Step 10
 
Now, you have to write the following code into the employee.component.ts file.
 
employee.component.ts
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2. import { FormBuilder, Validators } from '@angular/forms';  
  3. import { Observable } from 'rxjs';  
  4. import { EmployeeService } from '../employee.service';  
  5. import { Employee } from '../employee';  
  6. import { MatSnackBar, MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition } from '@angular/material/snack-bar';  
  7. import { MatDialog } from '@angular/material/dialog';  
  8. import { MatTableDataSource, } from '@angular/material/table';  
  9. import { MatPaginator } from '@angular/material/paginator';  
  10. import { MatSort } from '@angular/material/sort';  
  11. import { SelectionModel } from '@angular/cdk/collections';  
  12.    
  13.    
  14.    
  15. interface Country {  
  16.   CountryId: string;  
  17.   CountryName: string;  
  18. }  
  19. interface State {  
  20.   StateId: string;  
  21.   StateName: string;  
  22.   CountryId: string;  
  23. }  
  24. interface City {  
  25.   Cityid: string;  
  26.   CityName: string;  
  27.   StateId: string;  
  28.   CountryId: string;  
  29. }  
  30.    
  31.    
  32. @Component({  
  33.   selector: 'app-employee',  
  34.   templateUrl: './employee.component.html',  
  35.   styleUrls: ['./employee.component.css']  
  36. })  
  37. export class EmployeeComponent implements OnInit {  
  38.   dataSaved = false;  
  39.   employeeForm: any;  
  40.   allEmployees: Observable<Employee[]>;  
  41.   dataSource: MatTableDataSource<Employee>;  
  42.   selection = new SelectionModel<Employee>(true, []);  
  43.   employeeIdUpdate = null;  
  44.   massage = null;  
  45.   allCountry: Observable<Country[]>;  
  46.   allState: Observable<State[]>;  
  47.   allCity: Observable<City[]>;  
  48.   CountryId = null;  
  49.   StateId = null;  
  50.   CityId = null;  
  51.   SelectedDate = null;  
  52.   isMale = true;  
  53.   isFeMale = false;  
  54.   horizontalPosition: MatSnackBarHorizontalPosition = 'center';  
  55.   verticalPosition: MatSnackBarVerticalPosition = 'bottom';  
  56.   displayedColumns: string[] = ['select''FirstName''LastName''DateofBirth''EmailId''Gender''Country''State''City''Address''Pincode''Edit''Delete'];  
  57.   @ViewChild(MatPaginator) paginator: MatPaginator;  
  58.   @ViewChild(MatSort) sort: MatSort;  
  59.    
  60.    
  61.   constructor(private formbulider: FormBuilder, private employeeService: EmployeeService, private _snackBar: MatSnackBar, public dialog: MatDialog) {  
  62.     this.employeeService.getAllEmployee().subscribe(data => {  
  63.       this.dataSource = new MatTableDataSource(data);  
  64.       this.dataSource.paginator = this.paginator;  
  65.       this.dataSource.sort = this.sort;  
  66.     });  
  67.   }  
  68.    
  69.   ngOnInit() {  
  70.     this.employeeForm = this.formbulider.group({  
  71.       FirstName: ['', [Validators.required]],  
  72.       LastName: ['', [Validators.required]],  
  73.       DateofBirth: ['', [Validators.required]],  
  74.       EmailId: ['', [Validators.required]],  
  75.       Gender: ['', [Validators.required]],  
  76.       Address: ['', [Validators.required]],  
  77.       Country: ['', [Validators.required]],  
  78.       State: ['', [Validators.required]],  
  79.       City: ['', [Validators.required]],  
  80.       Pincode: ['', Validators.compose([Validators.required, Validators.pattern('[0-9]{6}')])]  
  81.     });  
  82.     this.FillCountryDDL();  
  83.     this.loadAllEmployees();  
  84.     this.dataSource.paginator = this.paginator;  
  85.     this.dataSource.sort = this.sort;  
  86.   }  
  87.    
  88.   isAllSelected() {  
  89.     const numSelected = this.selection.selected.length;  
  90.     const numRows = !!this.dataSource && this.dataSource.data.length;  
  91.     return numSelected === numRows;  
  92.   }  
  93.    
  94.   masterToggle() {  
  95.     this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(r => this.selection.select(r));  
  96.   }  
  97.    
  98.   checkboxLabel(row: Employee): string {  
  99.     if (!row) {  
  100.       return `${this.isAllSelected() ? 'select' : 'deselect'} all`;  
  101.     }  
  102.     return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.EmpId + 1}`;  
  103.   }  
  104.   DeleteData() {  
  105.     debugger;  
  106.     const numSelected = this.selection.selected;  
  107.     if (numSelected.length > 0) {  
  108.       if (confirm("Are you sure to delete items ")) {  
  109.         this.employeeService.deleteData(numSelected).subscribe(result => {  
  110.           this.SavedSuccessful(2);  
  111.           this.loadAllEmployees();  
  112.         })  
  113.       }  
  114.     } else {  
  115.       alert("Select at least one row");  
  116.     }  
  117.   }  
  118.    
  119.   applyFilter(filterValue: string) {  
  120.     this.dataSource.filter = filterValue.trim().toLowerCase();  
  121.    
  122.     if (this.dataSource.paginator) {  
  123.       this.dataSource.paginator.firstPage();  
  124.     }  
  125.   }  
  126.    
  127.   loadAllEmployees() {  
  128.     this.employeeService.getAllEmployee().subscribe(data => {  
  129.       this.dataSource = new MatTableDataSource(data);  
  130.       this.dataSource.paginator = this.paginator;  
  131.       this.dataSource.sort = this.sort;  
  132.     });  
  133.   }  
  134.   onFormSubmit() {  
  135.     this.dataSaved = false;  
  136.     const employee = this.employeeForm.value;  
  137.     this.CreateEmployee(employee);  
  138.     this.employeeForm.reset();  
  139.   }  
  140.   loadEmployeeToEdit(employeeId: string) {  
  141.     this.employeeService.getEmployeeById(employeeId).subscribe(employee => {  
  142.       this.massage = null;  
  143.       this.dataSaved = false;  
  144.       this.employeeIdUpdate = employee.EmpId;  
  145.       this.employeeForm.controls['FirstName'].setValue(employee.FirstName);  
  146.       this.employeeForm.controls['LastName'].setValue(employee.LastName);  
  147.       this.employeeForm.controls['DateofBirth'].setValue(employee.DateofBirth);  
  148.       this.employeeForm.controls['EmailId'].setValue(employee.EmailId);  
  149.       this.employeeForm.controls['Gender'].setValue(employee.Gender);  
  150.       this.employeeForm.controls['Address'].setValue(employee.Address);  
  151.       this.employeeForm.controls['Pincode'].setValue(employee.Pincode);  
  152.       this.employeeForm.controls['Country'].setValue(employee.CountryId);  
  153.       this.allState = this.employeeService.getState(employee.CountryId);  
  154.       this.CountryId = employee.CountryId;  
  155.       this.employeeForm.controls['State'].setValue(employee.StateId);  
  156.       this.allCity = this.employeeService.getCity(employee.StateId);  
  157.       this.StateId = employee.StateId;  
  158.       this.employeeForm.controls['City'].setValue(employee.Cityid);  
  159.       this.CityId = employee.Cityid;  
  160.       this.isMale = employee.Gender.trim() == "0" ? true : false;  
  161.       this.isFeMale = employee.Gender.trim() == "1" ? true : false;  
  162.     });  
  163.    
  164.   }  
  165.   CreateEmployee(employee: Employee) {  
  166.     console.log(employee.DateofBirth);  
  167.     if (this.employeeIdUpdate == null) {  
  168.       employee.CountryId = this.CountryId;  
  169.       employee.StateId = this.StateId;  
  170.       employee.Cityid = this.CityId;  
  171.    
  172.       this.employeeService.createEmployee(employee).subscribe(  
  173.         () => {  
  174.           this.dataSaved = true;  
  175.           this.SavedSuccessful(1);  
  176.           this.loadAllEmployees();  
  177.           this.employeeIdUpdate = null;  
  178.           this.employeeForm.reset();  
  179.         }  
  180.       );  
  181.     } else {  
  182.       employee.EmpId = this.employeeIdUpdate;  
  183.       employee.CountryId = this.CountryId;  
  184.       employee.StateId = this.StateId;  
  185.       employee.Cityid = this.CityId;  
  186.       this.employeeService.updateEmployee(employee).subscribe(() => {  
  187.         this.dataSaved = true;  
  188.         this.SavedSuccessful(0);  
  189.         this.loadAllEmployees();  
  190.         this.employeeIdUpdate = null;  
  191.         this.employeeForm.reset();  
  192.       });  
  193.     }  
  194.   }  
  195.   deleteEmployee(employeeId: string) {  
  196.     if (confirm("Are you sure you want to delete this ?")) {  
  197.       this.employeeService.deleteEmployeeById(employeeId).subscribe(() => {  
  198.         this.dataSaved = true;  
  199.         this.SavedSuccessful(2);  
  200.         this.loadAllEmployees();  
  201.         this.employeeIdUpdate = null;  
  202.         this.employeeForm.reset();  
  203.    
  204.       });  
  205.     }  
  206.    
  207.   }  
  208.    
  209.   FillCountryDDL() {  
  210.     this.allCountry = this.employeeService.getCountry();  
  211.     this.allState = this.StateId = this.allCity = this.CityId = null;  
  212.   }  
  213.    
  214.   FillStateDDL(SelCountryId) {  
  215.     this.allState = this.employeeService.getState(SelCountryId.value);  
  216.     this.CountryId = SelCountryId.value;  
  217.     this.allCity = this.CityId = null;  
  218.   }  
  219.    
  220.   FillCityDDL(SelStateId) {  
  221.     this.allCity = this.employeeService.getCity(SelStateId.value);  
  222.     this.StateId = SelStateId.value  
  223.   }  
  224.    
  225.   GetSelectedCity(City) {  
  226.     this.CityId = City.value;  
  227.   }  
  228.    
  229.   resetForm() {  
  230.     this.employeeForm.reset();  
  231.     this.massage = null;  
  232.     this.dataSaved = false;  
  233.     this.isMale = true;  
  234.     this.isFeMale = false;  
  235.     this.loadAllEmployees();  
  236.   }  
  237.    
  238.   SavedSuccessful(isUpdate) {  
  239.     if (isUpdate == 0) {  
  240.       this._snackBar.open('Record Updated Successfully!''Close', {  
  241.         duration: 2000,  
  242.         horizontalPosition: this.horizontalPosition,  
  243.         verticalPosition: this.verticalPosition,  
  244.       });  
  245.     }  
  246.     else if (isUpdate == 1) {  
  247.       this._snackBar.open('Record Saved Successfully!''Close', {  
  248.         duration: 2000,  
  249.         horizontalPosition: this.horizontalPosition,  
  250.         verticalPosition: this.verticalPosition,  
  251.       });  
  252.     }  
  253.     else if (isUpdate == 2) {  
  254.       this._snackBar.open('Record Deleted Successfully!''Close', {  
  255.         duration: 2000,  
  256.         horizontalPosition: this.horizontalPosition,  
  257.         verticalPosition: this.verticalPosition,  
  258.       });  
  259.     }  
  260.   }  
  261. }  
Step 11
 
As you can see, we have completed all the code and created two different projects for WEB API and Angular. Now, it's time to build and run our project.
 
So, first, build your project of WEB API and run it.
 
Now, it is time to build and run a project of Angular after successfully running the project of WEB API. To build the project of angular you have to write the following command in the package manager console.
 
Build an Angular Project
  1. ng build  
Run Angular Project
  1. ng serve -o  
When you press enter your angular project will run on URL: http://localhost:4200/
 
OUTPUT
 
Angular 11 Application using Web API With Material Design

Summary

 
In this article, we learned how to implement the CRUD operation using angular 11, WEB API, and SQL Server database, as well as we also learned how to use date piker in angular, radio buttons in angular as well as cascading dropdown using angular 11.

Comments