Date:

Share:

Angular 14 CRUD Example with Web API

Related Articles

In this article, we will learn the Angular Crud directory (create, read, update, delete) with the web API as well as implement data tables, tiered drop-down menus, search, sort and page using Angular 14. In this tutorial, we will use the SQL Server database and user interface Attractive and responsive for our web app, we will use the topic Angular Material.

In this tutorial, we use Visual Studio 2019 and here I explained how to create components, services, routes, pipelines, search, sort and layout in a simple way so that it is easy for beginners to understand.

In my previous articles, I have shared some articles on Angular 11, Angular 12 and Angular 13 as well as on AngularJS that you may want to read.

demand

  1. Create simple CRUD operations using Angular 14 with WEB API.
  2. Explain how to update the latest version of angular.
  3. Use an angular material topic.
  4. Launch the rated drop-down menu using Angular 14.

Application

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 a SQL server.

Level 1:

Here, we will create 4 different tables for storing employee information, as well as storing country, state and city information for a drop-down menu.

A desk worker

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)
);

Country

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 some sample entries to 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].[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)

level2:

Now, we need to create a WEB API to perform CRUD (create, replace, update and delete) operations for employees. To create a Web API, open the Visual studio 2019 >> File >> New >> Project >> Select a web application.

When you click on OK Button, another window will appear on your screen for selecting templates where you must select WebAPI and click the OK button.

Step 3:

Now, you need to go to the Solutions Explorer and right-click Model folder >> Add >> New item >> Select data from the left pane >> Select ADO.NET entity data model.

Now, click the Add button and select EF designer From the database >> the next >> Gives your SQL Server certificate And select the database. Now, you need to click the Add button and select your table and click on Finished button.

ADO.NET Entity Data Model

If you are starting out or need some help to add an entity data model, you can read this article where I explained how to create an entity data model of ADO.NET (EDM) in asp.net step by step.

Step 4:

Now, we will add a new blank controller to our web API project to create a WEB API to perform CRUD operations, and to do so, you need to go to the Solutions Explorer and right-click Controllers folder >> Add >> Controller >> Select Web API 2 Controller-Empty >> Click Add.

Now, you need to open our controller department 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 ex;
            }
            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 created all the required APIs and some of our API creation was done.

ASP.NET Web API

Now we need to focus on the angular part like installing Angular CLI, creating angular 14 project, consuming API using angular 14, commands for building and running angular application etc.

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

To install an angular CLI, open the package manager console or command line and type the command below, and press Enter.

npm install - g @angular/CLI

Note: If you are facing an issue related to npm, you need to download and install the active LTS, or maintain the LTS version of Node.js.

If you are running an older version of angular and would like to update your angular application to the latest version of angular, you can use the following command:

ng update @angular/cli@14 --force
ng update @angular/core@14 --force
ng update @angular/material@14 --force

Note: Update multiple major versions of ‘@ angular / CLI‘,’@ Angular / core‘and’@ Angular / Material‘At once unsupported. Please transfer each major version separately.

Let’s take one example, and check out the current version of angular.

To check the current version of ‘@ angular / CLI‘,’@ Angular / core‘, F’@ Angular / Material‘By using this command:

ng --version

Update multiple major versions of ‘@ angular / CLI‘,’@ Angular / core‘, F’@ Angular / Material‘At once unsupported. Please transfer each major version separately. So if your current version is 11 and you want to upgrade to the latest version 14, you need to run the following command:

Upgrade version 11 to 12

  1. run’ng update @ angular / CLI @ 12 –force‘In your workspace directory to update to the latest ’12 .x’ version of ‘@ angular / CLI’.
  2. run’Update @ angular / core @ 12 –force‘In your workspace directory to update to the latest ’12 .x’ version of ‘@ angular / core’.
  3. run’ng update @ angular / material @ 12 –force‘In your workspace directory to update to the latest version of ’12 .x’ of ‘@ angular / material’.

Then, upgrade version 12 to 13

  1. run’ng update @ angular / CLI @ 13 –force‘In your workspace directory to update to the latest ’13 .x’ version of ‘@ angular / CLI’.
  2. run’ng update @ angular / core @ 13 –force‘In your workspace directory to update to the latest ’13 .x’ version of ‘@ angular / core’.
  3. run’ng update @ angular / material @ 13 –force‘In your workspace directory to update to the latest ’13 .x’ version of ‘@ angular / material’.

Finally, upgrade version 13 to 14

  1. run’ng update @ angular / CLI @ 14 –force‘In your workspace directory to update to the latest ’14 .x’ version of ‘@ angular / CLI’.
  2. run’ng update @ angular / core @ 14 –force‘In your workspace directory to update to the latest ’14 .x’ version of ‘@ angular / core’.
  3. run’Update @ angular / material @ 14 –force‘In your workspace directory to update to the latest ’14 .x’ version of ‘@ angular / material’.

Now, we need to create a new angular project.

To create a new angular project, open the package manager console from API Project, type the following command, and press Enter.

ng new AngularCRUD

Here, AngularCRUD Is the name of our Angular project.

Now, we need to create a component in the created Angular project, for that we first need to change the directory and move to the Angular project, then 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 need to type the command as shown below and press Enter.

cd AngularCRUD

Now, we will create a component, for which you need to type the following command and press Enter.

Create a component

ng g c employee

where A Employee Is the name of component.

Step 6:

Now, we will create a service for which you need to type the following command and press Enter.

Create a service

ng g s employee

where is the Employee Is the name of service.

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

Your Angular Project Library

Now, we will create a class in an angular project identical to the model class, for which you need to write the following command.

Create a class

ng g class employee

Where the employee is is the name of the class.

Now, we will write down all the required characteristics of the employees as shown below in the created department.

Employee.ts

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 Angular project folderAnd open Employee.service.tsAnd import the necessary department 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 methods required for employ.service.ts to consume the API of the generated web.

As you can see in the code above, here we have taken the variable website address And assigned the website address or Web APIwhere http: // localhost: 59465 / Is the root website address Taken from the property as shown below, and / API / Works Is the URL prefix we added when creating the WEB API in the controller.

URL properties

When you need a web API from any Port or other domainangular will block the particular URL and we called this topic CORS (Cross-Resource Sharing)To resolve this issue you must log in WEB API Project >> Go to NuGet Package Manager >> Download “CORS” In the Web API project.

CORS

Now, you need to go to Explore Solutions >> Web API Project App_Start Folder >> WebApiConfig.cs status. In this file, you need to change the registration method and to do so, you need to write the following code as shown below.

Add namespace

using System.Web.Http.Cors;

Now, write the following code using the registration method.

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

Step 7:

Now, we need to install Angular Material theme, open the package manager console and write the following code.

npm install--save @angular/material @angular/cdk @angular/animations

If you are using an angular material theme, and you want to update to the latest version of angular material, you can use the following command:

ng update @angular/material --force

You can check the package.json file in the Angular project to see if the Material theme is installed or not.

package.json

{
  "name""angular-crud",
  "version""0.0.0",
  "scripts": {
    "ng""ng",
    "start""ng serve",
    "build""ng build",
    "test""ng test",
    "lint""ng lint",
    "e2e""ng e2e"
  },
  "private"true,
  "dependencies": {
    "@angular/animations""^14.0.0",
    "@angular/cdk""^14.0.0",
    "@angular/common""^14.0.0",
    "@angular/compiler""^14.0.0",
    "@angular/core""^14.0.0",
    "@angular/forms""^14.0.0",
    "@angular/material""^14.0.0",
    "@angular/platform-browser""^14.0.0",
    "@angular/platform-browser-dynamic""^14.0.0",
    "@angular/router""^14.0.0",
    "mat-table-exporter""^9.0.2",
    "ng-marquee""^9.5.0",
    "rxjs""~6.6.0",
    "tslib""^2.0.0",
    "zone.js""~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular""^14.0.0",
    "@angular/cli""^14.0.0",
    "@angular/compiler-cli""^14.0.0",
    "@types/jasmine""~3.6.0",
    "@types/node""^12.11.1",
    "codelyzer""^6.0.0",
    "jasmine-core""~3.6.0",
    "jasmine-spec-reporter""~5.0.0",
    "karma""~6.3.20",
    "karma-chrome-launcher""~3.1.0",
    "karma-coverage""~2.0.3",
    "karma-jasmine""~4.0.0",
    "karma-jasmine-html-reporter""^1.5.0",
    "protractor""~7.0.0",
    "ts-node""~8.3.0",
    "tslint""~6.1.0",
    "typescript""~4.6.4"
  }
}

Now, you need to import all the required directories app.module.ts As shown below.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { EmployeeService } from './employee.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';


import { HttpClientModule, HttpClient } from '@angular/common/http';
import { MatInputModule } from "@angular/material/input";
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule } from '@angular/material/core';
import { MatIconModule } from '@angular/material/icon';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatRadioModule } from '@angular/material/radio';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatSelectModule } from '@angular/material/select';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { CdkTableModule } from '@angular/cdk/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { NgMarqueeModule } from 'ng-marquee';
import { MatDialogModule } from '@angular/material/dialog';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatButtonModule,
    MatMenuModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatIconModule,
    MatRadioModule,
    MatCardModule,
    MatSidenavModule,
    MatFormFieldModule,
    MatInputModule,
    MatTooltipModule,
    MatToolbarModule,
    AppRoutingModule,
    MatCheckboxModule,
    MatSelectModule,
    MatSnackBarModule,
    MatTableModule,
    CdkTableModule,
    MatPaginatorModule,
    NgMarqueeModule,
    MatDialogModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, you must Import the CSS Of the subject of angular matter in styles.css File as shown below. There are many different material topics available, you can follow this official document of Angular material.

styles.css

@import '@angular/material/prebuilt-themes/indigo-pink.css';

Step 8:

Now, you need to write the following HTML Code in employee.component.html file.

employee.component.html

<div class="container">
 
  <mat-card class="mat-elevation-z8">
    <mat-toolbar color="accent" style="box-shadow0 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);">
      <div align="center" style="text-alignright;">
        Codingvila | Angular 14 CRUD Example with Web API
      </div>
    </mat-toolbar>
    <br><br>
    <mat-card-content>
      <form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit()">
        <table>
          <tr>
            <td class="tbl1">
              <mat-form-field class="demo-full-width">
                <input formControlName="FirstName" matTooltip="Enter Employee FirstName" matInput placeholder="FirstName" autocomplete="off">
              </mat-form-field>
              <mat-error>
                <span *ngIf="!employeeForm.get('FirstName').value && employeeForm.get('FirstName').touched"></span>
              </mat-error>
            </td>
            <td class="tbl1">
              <mat-form-field class="demo-full-width">
                <input formControlName="LastName" matTooltip="Enter Employee LastName" matInput placeholder="LastName" autocomplete="off">
              </mat-form-field>
              <mat-error>
                <span *ngIf="!employeeForm.get('LastName').value && employeeForm.get('LastName').touched"></span>
              </mat-error>
            </td>
            <td class="tbl1">
              <mat-form-field class="demo-full-width">
                <input matInput [matDatepicker]="picker" matTooltip="Enter Date Of Birth" formControlName="DateofBirth" placeholder="Date Of Birth" autocomplete="off">
                <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
              </mat-form-field>
              <mat-error>
                <span *ngIf="!employeeForm.get('DateofBirth').value && employeeForm.get('DateofBirth').touched"></span>
              </mat-error>
            </td>
            <td class="tbl1">
              <mat-form-field class="demo-full-width">
                <input formControlName="EmailId" matTooltip="Enter EmailId" matInput placeholder="Email ID" autocomplete="off">
              </mat-form-field>
              <mat-error>
                <span *ngIf="!employeeForm.get('EmailId').value && employeeForm.get('EmailId').touched"></span>
              </mat-error>
            </td>
            <td class="tbl1">
              <span>Gender</span>&nbsp;
 
              <mat-radio-group matTooltip="Enter Gender" formControlName="Gender">
                <mat-radio-button value="0" [checked]="isMale">Male</mat-radio-button>&nbsp;&nbsp;
                <mat-radio-button value="1" [checked]="isFeMale">Female</mat-radio-button>&nbsp;&nbsp;
              </mat-radio-group>
              <mat-error>
                <span *ngIf="!employeeForm.get('Gender').value && employeeForm.get('Gender').touched"></span>
              </mat-error>
            </td>
          </tr>
          <tr>
            <td class="tbl1">
              <mat-form-field>
                <mat-label>Country</mat-label>
                <mat-select (selectionChange)="FillStateDDL($event)" formControlName="Country" matTooltip="Select Country" autocomplete="off">
                  <mat-option *ngFor="let Country of (allCountry | async)" [value]="Country.CountryId">
                    {{Country.CountryName}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </td>
            <td class="tbl1">
              <mat-form-field>
                <mat-label>State</mat-label>
                <mat-select (selectionChange)="FillCityDDL($event)" formControlName="State" matTooltip="Select State" autocomplete="off">
                  <mat-option *ngFor="let State of (allState | async)" [value]="State.StateId">
                    {{State.StateName}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </td>
            <td class="tbl1">
              <mat-form-field>
                <mat-label>City</mat-label>
                <mat-select formControlName="City" (selectionChange)="GetSelectedCity($event)" matTooltip="Select City" autocomplete="off">
                  <mat-option *ngFor="let City of (allCity | async)" [value]="City.Cityid">
                    {{City.CityName}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </td>
            <td class="tbl1">
              <mat-form-field class="demo-full-width">
                <input matTooltip="Enter Address" formControlName="Address" matInput placeholder="Address" autocomplete="off">
              </mat-form-field>
              <mat-error>
                <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>
              </mat-error>
            </td>
            <td class="tbl1">
              <mat-form-field class="demo-full-width">
                <input formControlName="Pincode" matTooltip="Enter Pine Code" matInput placeholder="Pincode" minLength="5" maxLength="6" autocomplete="off">
              </mat-form-field>
              <mat-error>
                <span *ngIf="!employeeForm.get('Pincode').value && employeeForm.get('Pincode').touched"></span>
              </mat-error>
            </td>
          </tr>
          <tr>
            <td class="content-center">
              <button type="submit" mat-raised-button color="accent" matTooltip="Submit" [disabled]="!employeeForm.valid">Submit</button>&nbsp;&nbsp;&nbsp;&nbsp;
              <button type="reset" mat-raised-button color="accent" matTooltip="Reset" (click)="resetForm()">Reset</button>
            </td>
            <td>
              <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">
                {{massage}}
              </p>
            </td>
            <td></td>
            <td></td>
          </tr>
        </table>
        <br><br>
        <b>Search Records :</b> &nbsp;&nbsp;
        <mat-form-field>
          <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
        </mat-form-field>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <b>Delete Selected Records :</b> &nbsp;&nbsp;
        <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>
 
        <div>
 
          <mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8" style="box-shadow0 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);">
 
            <!-- Checkbox Column -->
            <ng-container matColumnDef="select">
              <mat-header-cell *matHeaderCellDef>
                <mat-checkbox (change)="$event ? masterToggle() : null"
                              [checked]="selection.hasValue() && isAllSelected()"
                              [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
              </mat-header-cell>
              <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>
              </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="FirstName">
              <mat-header-cell *matHeaderCellDef mat-sort-header> First Name </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.FirstName}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="LastName">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Last Name </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.LastName}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="DateofBirth">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Date Of Birth </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.DateofBirth | date:'dd-MM-yyyy'}}</mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="EmailId">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Email Id </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.EmailId}}        </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="Gender">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Gender </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.Gender ==0? 'Male' : 'Female'}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="Country">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Country </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.Country}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="State">
              <mat-header-cell *matHeaderCellDef mat-sort-header> State </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.State}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="City">
              <mat-header-cell *matHeaderCellDef mat-sort-header> City </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.City}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="Address">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Address </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.Address}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="Pincode">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Pincode </mat-header-cell>
              <mat-cell *matCellDef="let employee"> {{employee.Pincode}} </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="Edit">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Edit </mat-header-cell>
 
              <mat-cell *matCellDef="let employee">
 
                <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>
                <!--<button mat-icon-button aria-label="Example icon button with a vertical three dot icon" color="accent" matTooltip="Edit" (click)="loadEmployeeToEdit(employee.EmpId)">
            <mat-icon>more_vert</mat-icon>
          </button>-->
              </mat-cell>
            </ng-container>
 
            <ng-container matColumnDef="Delete">
              <mat-header-cell *matHeaderCellDef mat-sort-header> Delete </mat-header-cell>
              <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></mat-cell>
            </ng-container>
 
            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
          </mat-table>
 
          <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
        </div>
      </form>
    </mat-card-content>
  </mat-card>
</div>

Step 9:

Now, you need to write the following code into app.component.html file.

app.component.html

<p>
  <app-employee></app-employee>
</p>

Step 10:

Now, you need to write the following code into Employee.Component.Tess file.

Employee.Component.Tess

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { EmployeeService } from '../employee.service';
import { Employee } from '../employee';
import { MatSnackBar, MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource, } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { SelectionModel } from '@angular/cdk/collections';
 
interface Country {
  CountryId: string;
  CountryName: string;
}
 
interface State {
  StateId: string;
  StateName: string;
  CountryId: string;
}
 
interface City {
  Cityid: string;
  CityName: string;
  StateId: string;
  CountryId: string;
}
 
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
 
export class EmployeeComponent implements OnInit {
  dataSaved = false;
  employeeForm: any;
  allEmployees: Observable<Employee[]>;
  dataSource: MatTableDataSource<Employee>;
  selection = new SelectionModel<Employee>(true, []);
  employeeIdUpdate = null;
  massage = null;
  allCountry: Observable<Country[]>;
  allState: Observable<State[]>;
  allCity: Observable<City[]>;
  CountryId = null;
  StateId = null;
  CityId = null;
  SelectedDate = null;
  isMale = true;
  isFeMale = false;
  horizontalPosition: MatSnackBarHorizontalPosition = 'center';
  verticalPosition: MatSnackBarVerticalPosition = 'bottom';
  displayedColumns: string[] = ['select''FirstName''LastName''DateofBirth''EmailId''Gender''Country''State''City''Address''Pincode''Edit''Delete'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
 
  constructor(private formbulider: FormBuilder, private employeeService: EmployeeService, private _snackBar: MatSnackBar, public dialog: MatDialog) {
    this.employeeService.getAllEmployee().subscribe(data => {
      this.dataSource = new MatTableDataSource(data);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });
  }
 
  ngOnInit() {
    this.employeeForm = this.formbulider.group({
      FirstName: ['', [Validators.required]],
      LastName: ['', [Validators.required]],
      DateofBirth: ['', [Validators.required]],
      EmailId: ['', [Validators.required]],
      Gender: ['', [Validators.required]],
      Address: ['', [Validators.required]],
      Country: ['', [Validators.required]],
      State: ['', [Validators.required]],
      City: ['', [Validators.required]],
      Pincode: ['', Validators.compose([Validators.required, Validators.pattern('[0-9]{6}')])]
    });
    this.FillCountryDDL();
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
 
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = !!this.dataSource && this.dataSource.data.length;
    return numSelected === numRows;
  }
 
 /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(r => this.selection.select(r));
  }
  /** The label for the checkbox on the passed row */
  checkboxLabel(row: Employee): string {
    if (!row) {
      return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.EmpId + 1}`;
  }
  
  DeleteData() {
    debugger;
    const numSelected = this.selection.selected;
    if (numSelected.length > 0) {
      if (confirm("Are you sure to delete items ")) {
        this.employeeService.deleteData(numSelected).subscribe(result => {
          this.SavedSuccessful(2);
          this.loadAllEmployees();
        })
      }
    } else {
      alert("Select at least one row");
    }
  }
 
  applyFilter(filterValuestring) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
 
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
 
  loadAllEmployees() {
    this.employeeService.getAllEmployee().subscribe(data => {
      this.dataSource = new MatTableDataSource(data);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });
  }
  onFormSubmit() {
    this.dataSaved = false;
    const employee = this.employeeForm.value;
    this.CreateEmployee(employee);
    this.employeeForm.reset();
  }
 
  loadEmployeeToEdit(employeeIdstring) {
    this.employeeService.getEmployeeById(employeeId).subscribe(employee => {
      this.massage = null;
      this.dataSaved = false;
      this.employeeIdUpdate = employee.EmpId;
      this.employeeForm.controls['FirstName'].setValue(employee.FirstName);
      this.employeeForm.controls['LastName'].setValue(employee.LastName);
      this.employeeForm.controls['DateofBirth'].setValue(employee.DateofBirth);
      this.employeeForm.controls['EmailId'].setValue(employee.EmailId);
      this.employeeForm.controls['Gender'].setValue(employee.Gender);
      this.employeeForm.controls['Address'].setValue(employee.Address);
      this.employeeForm.controls['Pincode'].setValue(employee.Pincode);
      this.employeeForm.controls['Country'].setValue(employee.CountryId);
      this.allState = this.employeeService.getState(employee.CountryId);
      this.CountryId = employee.CountryId;
      this.employeeForm.controls['State'].setValue(employee.StateId);
      this.allCity = this.employeeService.getCity(employee.StateId);
      this.StateId = employee.StateId;
      this.employeeForm.controls['City'].setValue(employee.Cityid);
      this.CityId = employee.Cityid;
      this.isMale = employee.Gender.trim() == "0" ? true : false;
      this.isFeMale = employee.Gender.trim() == "1" ? true : false;
    });
 
  }
  CreateEmployee(employee: Employee) {
    console.log(employee.DateofBirth);
    if (this.employeeIdUpdate == null) {
      employee.CountryId = this.CountryId;
      employee.StateId = this.StateId;
      employee.Cityid = this.CityId;
 
      this.employeeService.createEmployee(employee).subscribe(
        () => {
          this.dataSaved = true;
          this.SavedSuccessful(1);
          this.loadAllEmployees();
          this.employeeIdUpdate = null;
          this.employeeForm.reset();
        }
      );
    } else {
      employee.EmpId = this.employeeIdUpdate;
      employee.CountryId = this.CountryId;
      employee.StateId = this.StateId;
      employee.Cityid = this.CityId;
      this.employeeService.updateEmployee(employee).subscribe(() => {
        this.dataSaved = true;
        this.SavedSuccessful(0);
        this.loadAllEmployees();
        this.employeeIdUpdate = null;
        this.employeeForm.reset();
      });
    }
  }
  deleteEmployee(employeeIdstring) {
    if (confirm("Are you sure you want to delete this ?")) {
      this.employeeService.deleteEmployeeById(employeeId).subscribe(() => {
        this.dataSaved = true;
        this.SavedSuccessful(2);
        this.loadAllEmployees();
        this.employeeIdUpdate = null;
        this.employeeForm.reset();
 
      });
    }
 
  }
 
  FillCountryDDL() {
    this.allCountry = this.employeeService.getCountry();
    this.allState = this.StateId = this.allCity = this.CityId = null;
  }
 
  FillStateDDL(SelCountryId) {
    this.allState = this.employeeService.getState(SelCountryId.value);
    this.CountryId = SelCountryId.value;
    this.allCity = this.CityId = null;
  }
 
  FillCityDDL(SelStateId) {
    this.allCity = this.employeeService.getCity(SelStateId.value);
    this.StateId = SelStateId.value
  }
 
  GetSelectedCity(City) {
    this.CityId = City.value;
  }
 
  resetForm() {
    this.employeeForm.reset();
    this.massage = null;
    this.dataSaved = false;
    this.isMale = true;
    this.isFeMale = false;
    this.loadAllEmployees();
  }
 
  SavedSuccessful(isUpdate) {
    if (isUpdate == 0) {
      this._snackBar.open('Record Updated Successfully!''Close', {
        duration: 2000,
        horizontalPosition: this.horizontalPosition,
        verticalPosition: this.verticalPosition,
      });
    } 
    else if (isUpdate == 1) {
      this._snackBar.open('Record Saved Successfully!''Close', {
        duration: 2000,
        horizontalPosition: this.horizontalPosition,
        verticalPosition: this.verticalPosition,
      });
    }
    else if (isUpdate == 2) {
      this._snackBar.open('Record Deleted Successfully!''Close', {
        duration: 2000,
        horizontalPosition: this.horizontalPosition,
        verticalPosition: this.verticalPosition,
      });
    }
  }
}

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 WEB API project and launch it.

Now, it’s time to build and run Angular project after successfully running the WEB API project. To build the angular project, you must write the following command in the Package Manager console.

Construction of an angular project

Launch the Angular project

When you press Enter, your angular project will run at the URL: http: // localhost: 4200 /

Summary

In this article, we learned how to implement the CRUD operation using angular 14 with Web API and SQL Server database, we also learned how to use Angle Date piker, angle radio buttons and also graded using angular 14.

Please leave your comments and share a link to this article if you would like.

Source

Popular Articles