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

- Create a simple CRUD operation using Angular 11 and WEB API.
- 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.
- Implement cascading dropdown using angular 11.
Implementation
- 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)
- );
- CREATE TABLE [dbo].[CountryMaster] (
- [CountryId] INT IDENTITY (1, 1) NOT NULL,
- [CountryName] VARCHAR (50) NULL,
- CONSTRAINT [PK_CountryMaster] PRIMARY KEY CLUSTERED ([CountryId] ASC)
- );
- 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)
- );
- 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)
- );
- INSERT [dbo].[CountryMaster] ([CountryName]) VALUES (N'India')
- INSERT [dbo].[CountryMaster] ([CountryName]) VALUES (N'United States')
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Andhra Pradesh', 1)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Gujarat', 1)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Kerala', 1)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Alabama', 2)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Hawaii', 2)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'Texas', 2)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'New Mexico', 2)
- INSERT [dbo].[StateMaster] ([StateName], [CountryId]) VALUES (N'New York', 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Visakhapatnam', 1, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vijayawada', 1, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Guntur', 1, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Nellore', 1, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kurnool', 1, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Ahmedabad', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Surat', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vadodara', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Rajkot', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Bhavnagar', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Jamnagar', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Junagadh', 2, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Thiruvananthapuram', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kochi', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kozhikode', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kollam', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kannur', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Malappuram', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Vatakara', 3, 1)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Adamsville', 4, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Addison', 4, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Allgood', 4, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Auburn', 4, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Honolulu', 5, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'East Honolulu', 5, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Kahului', 5, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Abernathy', 6, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Alton', 6, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Barstow', 6, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Bellmead', 6, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Angel Fire', 7, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Capitan', 7, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Dexter', 7, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Floyd', 7, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Albany', 8, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Geneva', 8, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Olean', 8, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'White Plains', 8, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Rome', 8, 2)
- INSERT [dbo].[CityMaster] ([CityName], [StateId], [CountryId]) VALUES (N'Troy', 8, 2)

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

- cd NameofYourAngulerProject
- cd AngularCRUD
- ng g c employee
- ng g s employee

- ng g class employee
- export class Employee {
- EmpId: string;
- FirstName: string;
- LastName: string;
- DateofBirth: Date;
- EmailId: string;
- Gender: string;
- CountryId: string;
- StateId: string;
- Cityid: string;
- Address: string;
- Pincode: string;
- Country: string;
- State: string;
- City: string;
- }
- export class Country {
- CountryId: string;
- CountryName: string;
- }
- export class State {
- StateId: string;
- StateName: string;
- CountryId: string;
- }
- export class City {
- Cityid: string;
- CityName: string;
- StateId: string;
- CountryId: string;
- }
- 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';
- @Injectable({
- providedIn: 'root'
- })
- export class EmployeeService {
- url = 'http://localhost:59465/Api/Employee';
- constructor(private http: HttpClient) { }
- getAllEmployee(): Observable<Employee[]> {
- return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');
- }
- getEmployeeById(employeeId: string): Observable<Employee> {
- return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);
- }
- createEmployee(employee: Employee): Observable<Employee> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
- return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',
- employee, httpOptions);
- }
- updateEmployee(employee: Employee): Observable<Employee> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
- return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',
- employee, httpOptions);
- }
- deleteEmployeeById(employeeid: string): Observable<number> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
- return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' + employeeid,
- httpOptions);
- }
- getCountry(): Observable<Country[]> {
- return this.http.get<Country[]>(this.url + '/Country');
- }
- getState(CountryId: string): Observable<State[]> {
- return this.http.get<State[]>(this.url + '/Country/' + CountryId + '/State');
- }
- getCity(StateId: string): Observable<City[]> {
- return this.http.get<City[]>(this.url + '/State/' + StateId + '/City');
- }
- deleteData(user: Employee[]): Observable<string> {
- const httpOptions = {
- headers: new HttpHeaders({
- 'Content-Type': 'application/json'
- })
- };
- return this.http.post<string>(this.url + '/DeleteRecord/', user, httpOptions);
- }
- }


- using System.Web.Http.Cors;
- var cors = new EnableCorsAttribute("*", "*", "*");//origins,headers,methods
- config.EnableCors(cors);
- npm install --save @angular/material @angular/cdk @angular/animations
- {
- "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": "^11.0.2",
- "@angular/cdk": "^11.0.1",
- "@angular/common": "~11.0.1",
- "@angular/compiler": "~11.0.1",
- "@angular/core": "~11.0.1",
- "@angular/forms": "~11.0.1",
- "@angular/material": "^11.0.1",
- "@angular/platform-browser": "~11.0.1",
- "@angular/platform-browser-dynamic": "~11.0.1",
- "@angular/router": "~11.0.1",
- "rxjs": "~6.6.0",
- "tslib": "^2.0.0",
- "zone.js": "~0.10.2"
- },
- "devDependencies": {
- "@angular-devkit/build-angular": "~0.1100.2",
- "@angular/cli": "^11.0.2",
- "@angular/compiler-cli": "~11.0.1",
- "@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": "~5.1.0",
- "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.0.2"
- }
- }
- 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';
- @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
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
- @import '@angular/material/prebuilt-themes/indigo-pink.css';
- <div class="container">
- <mat-card class="mat-elevation-z8">
- <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);">
- <div align="center" style="color:white;text-align: right;">
- Codingvila | Angular 11 Application using Web API With Material Design
- </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>
- <mat-radio-group matTooltip="Enter Gender" formControlName="Gender">
- <mat-radio-button value="0" [checked]="isMale">Male</mat-radio-button>
- <mat-radio-button value="1" [checked]="isFeMale">Female</mat-radio-button>
- </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>
- <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>
- <mat-form-field>
- <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
- </mat-form-field>
- <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>
- <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);">
- <!-- Checkbox Column -->
- <ng-container matColumnDef="select">
- <th style="width: 100px;" mat-header-cell *matHeaderCellDef>
- <mat-checkbox (change)="$event ? masterToggle() : null"
- [checked]="selection.hasValue() && isAllSelected()"
- [indeterminate]="selection.hasValue() && !isAllSelected()"></mat-checkbox>
- </th>
- <td mat-cell *matCellDef="let row">
- <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null"
- [checked]="selection.isSelected(row)" [aria-label]="checkboxLabel(row)"></mat-checkbox>
- </td>
- </ng-container>
- <ng-container matColumnDef="FirstName">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> First Name </th>
- <td mat-cell *matCellDef="let employee"> {{employee.FirstName}} </td>
- </ng-container>
- <ng-container matColumnDef="LastName">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Last Name </th>
- <td mat-cell *matCellDef="let employee"> {{employee.LastName}} </td>
- </ng-container>
- <ng-container matColumnDef="DateofBirth">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Date Of Birth </th>
- <td mat-cell *matCellDef="let employee"> {{employee.DateofBirth | date:'dd-MM-yyyy'}}</td>
- </ng-container>
- <ng-container matColumnDef="EmailId">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Email Id </th>
- <td mat-cell *matCellDef="let employee"> {{employee.EmailId}} </td>
- </ng-container>
- <ng-container matColumnDef="Gender">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Gender </th>
- <td mat-cell *matCellDef="let employee"> {{employee.Gender ==0? 'Male' : 'Female'}} </td>
- </ng-container>
- <ng-container matColumnDef="Country">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Country </th>
- <td mat-cell *matCellDef="let employee"> {{employee.Country}} </td>
- </ng-container>
- <ng-container matColumnDef="State">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> State </th>
- <td mat-cell *matCellDef="let employee"> {{employee.State}} </td>
- </ng-container>
- <ng-container matColumnDef="City">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> City </th>
- <td mat-cell *matCellDef="let employee"> {{employee.City}} </td>
- </ng-container>
- <ng-container matColumnDef="Address">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Address </th>
- <td mat-cell *matCellDef="let employee"> {{employee.Address}} </td>
- </ng-container>
- <ng-container matColumnDef="Pincode">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Pincode </th>
- <td mat-cell *matCellDef="let employee"> {{employee.Pincode}} </td>
- </ng-container>
- <ng-container matColumnDef="Edit">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Edit </th>
- <td 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>
- </td>
- </ng-container>
- <ng-container matColumnDef="Delete">
- <th mat-header-cell *matHeaderCellDef mat-sort-header> Delete </th>
- <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>
- </ng-container>
- <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
- <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
- </table>
- <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
- </div>
- </form>
- </mat-card-content>
- </mat-card>
- </div>
- <p>
- <app-employee></app-employee>
- </p>
- 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.loadAllEmployees();
- 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;
- }
- masterToggle() {
- this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(r => this.selection.select(r));
- }
- 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(filterValue: string) {
- 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(employeeId: string) {
- 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(employeeId: string) {
- 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,
- });
- }
- }
- }
- ng build
- ng serve -o

Comments
Post a Comment