ASP .NET Core Web API CRUD with Angular Using EF Core Code First | Hindi/Urdu ✅

Introduction

Welcome to LogicTycoon blog. In this blog you will learn complete step by step ASP .NET Core Web API CRUD with Angular application Using EF(Entity Framework) Core Code First Approach with animated data entry form. We will perform all operation like POST, PUT, DELETE, GET methods and build asp .net core web api and consume that api in angular frontend app. We will learn how to enable cors in web api

Step 1- Project Setup

Add Asp .Net Core Project

Create the Asp.Net Core Web Api project using the Visual Studio in Asp.net Core with the latest version of .Net Core (if you have older version that's also work)


Step 2- Add Packages

Install Required Packages from Nuget Package Manager

Open solution explorer and right click on Dependencies and open Manage Nuget Packages(Nuget Package Manager) and install following packages :

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Design
Note : Packages version should be same according to your project .net core version.


Step 3- Add Model Classes

Create Entity classes in Model Folder

Open solution explorer right click on model folder and create classes with following Names:

  • TblEmployee.cs
  • TblDesignation.cs


Create Properties In TblEmployee.cs Class

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;  
  namespace WebApiCoreNew.Model
  {   
   public class TblEmployee
   {
       public int Id { get; set; }
       public string Name { get; set; }
       public string LastName { get; set; }
       public string Email { get; set; }
       public int Age { get; set; }
       public DateTime Doj { get; set; }
       public string Gender { get; set; }
       public int IsMarried { get; set; }
       public int IsActive { get; set; }
       public int DesignationID { get; set; }
       public string Designation { get; set; }
   }
  }

Create Properties In TblDesignation.cs Class

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;  
  namespace WebApiCoreNew.Model
  {   
   public class TblDesignation
   {
       public int Id { get; set; }
       public string Designation { get; set; }
   }
  }

Soft Introduction of Entity Framework Code First

In the Entity Framework Code First approach we create database and tables by the application classes and configuration rather than design your database first and then create the classes which match your database design. So in simple words we used the above created classes as a table in database after run Migration commands.

Before proceed migrations we have to update classes properties with some important changes. we have to add some DataAnnotations along with model class and properties. DataAnnotations used for add labeling, highlight the most commonly needed configuration and validations to model class and entities.

In our case, we are using DataAnnotations to add the PrimaryKey to the Id column and set the string characters limit to string properties and make the primary key Id auto-generated with increment 1.


Now the updated TblEmployee class code is

  using System;
  using System.Collections.Generic;
  using System.ComponentModel.DataAnnotations;
  using System.ComponentModel.DataAnnotations.Schema;
  using System.Linq;
  using System.Threading.Tasks;
  namespace WebApiCoreNew.Model
  { public class TblEmployee
   {
       [Key]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public int Id { get; set; }
       [StringLength(150)]
       public string Name { get; set; }
       [StringLength(150)]
       public string LastName { get; set; }
       [StringLength(250)]
       public string Email { get; set; }
       public int Age { get; set; }
       public DateTime Doj { get; set; }
       [StringLength(50)]
       public string Gender { get; set; }
       public int IsMarried { get; set; }
       public int IsActive { get; set; }
       public int DesignationID { get; set; }
       [NotMapped]
       public string Designation { get; set; }
   }
  }

Updated code of TblDesignation Class is

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.ComponentModel.DataAnnotations;
  using System.ComponentModel.DataAnnotations.Schema;
  using System.Threading.Tasks;  
  namespace WebApiCoreNew.Model
  {   
   public class TblDesignation
   {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int Id { get; set; }
      [StringLength(250)]
      public string Designation { get; set; }
   }
  }

Step 4- Add DbContext Class

Create another class in model folder for DbContext with name EmployeeContext.cs

  using Microsoft.EntityFrameworkCore;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  
  namespace WebApiCoreNew.Model
  {
     public class EmployeeContext : DbContext
     {
       public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)
       {
       }
       public DbSet<TblEmployee> TblEmployee { get; set; }
       public DbSet<TblDesignation> TblDesignation { get; set; }
     }
  }

Step 5- Add ConnectionString

Open appsettings.json and add connection string

 "ConnectionStrings": {
    "EmpCon": "Server=192.168.10.239; Database=testDB; User Id=sa;password=dotnet123@;;Trusted_Connection=False;MultipleActiveResultSets=true;"
  },			
		

Step 6- Go to Startup.cs file

Open Startup.cs and add update ConfigureServices and Configure method

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddDbContext<EmployeeContext>(db => db.UseSqlServer(Configuration.GetConnectionString("ConEmp")));

    //This code used for add cors helps to resolve cross-origin error 
    services.AddCors(cors => cors.AddPolicy("MyPolicy", builder => {
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
      }));
 }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
      app.UseDeveloperExceptionPage();
  }

   app.UseHttpsRedirection();
   app.UseRouting();
   app.UseCors("MyPolicy");
   app.UseAuthorization();

   app.UseEndpoints(endpoints =>
   {
       endpoints.MapControllers();
   });
}

Step 7- Create Web Api Controller

Goto Solution Explorer and right click Controller folder and add new controller

!Note : Controllers should be Api Controller


EmployeeController Code

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApiCoreLecture.Model;

namespace WebApiCoreLecture.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly EmployeeContext _context;

        public EmployeeController(EmployeeContext context)
        {
            _context = context;
        }

        // GET: api/Employee
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TblEmployee>>> GetTblEmployee()
        {
            //return await _context.TblEmployee.ToListAsync();

            var employees = (from e in _context.TblEmployee
                             join d in _context.TblDesignation
                             on e.DesignationID equals d.Id

                             select new TblEmployee
                             {
                                 Id = e.Id,
                                 Name = e.Name,
                                 LastName = e.LastName,
                                 Email = e.Email,
                                 Age = e.Age,
                                 DesignationID = e.DesignationID,
                                 Designation = d.Designation,
                                 Doj = e.Doj,
                                 Gender = e.Gender,
                                 IsActive = e.IsActive,
                                 IsMarried=e.IsMarried
                             }
                            ).ToListAsync();




            return await employees;
        }

        // GET: api/Employee/5
        [HttpGet("{id}")]
        public async Task<ActionResult<TblEmployee>> GetTblEmployee(int id)
        {
            var tblEmployee = await _context.TblEmployee.FindAsync(id);

            if (tblEmployee == null)
            {
                return NotFound();
            }

            return tblEmployee;
        }

        
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTblEmployee(int id, TblEmployee tblEmployee)
        {
            if (id != tblEmployee.Id)
            {
                return BadRequest();
            }

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

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TblEmployeeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        [HttpPost]
        public async Task<ActionResult<TblEmployee>> PostTblEmployee(TblEmployee tblEmployee)
        {
            _context.TblEmployee.Add(tblEmployee);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTblEmployee", new { id = tblEmployee.Id }, tblEmployee);
        }

        // DELETE: api/Employee/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<TblEmployee>> DeleteTblEmployee(int id)
        {
            var tblEmployee = await _context.TblEmployee.FindAsync(id);
            if (tblEmployee == null)
            {
                return NotFound();
            }

            _context.TblEmployee.Remove(tblEmployee);
            await _context.SaveChangesAsync();

            return tblEmployee;
        }

        private bool TblEmployeeExists(int id)
        {
            return _context.TblEmployee.Any(e => e.Id == id);
        }
    }
}

DesignationController.cs file code

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApiCoreLecture.Model;

namespace WebApiCoreLecture.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DesignationController : ControllerBase
    {
        private readonly EmployeeContext _context;
        public DesignationController(EmployeeContext context)
        {
            _context = context;
        }
        // GET: api/lDesignation
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TblDesignation>>> GetTblDesignation()
        {
            return await _context.TblDesignation.ToListAsync();
        }
    }
}

Step 8- Run Migrations Script

Goto Tools> Nuget Package Manager> Package Manager Console and run these followings commands in Package Manager Console window

  • add-migration init
  • update-database

If migrations succeed then you will get the database and all related tables in Db Server.


Step 9- Create Angular App

Open visual studio code and create new angular project

open terminal in vs code and type ng new command with project name

Ex: ng new Init


Step 10- Create Employee and Designation Model Class

Run this command in terminal window

ng g class shared/Employee --type=model
export class Epmloyee
 {
    id:number=0;
    name:string;
    lastName: string='';
    email: string='';
    age: number;
    doj: any;
    gender: string='male';
    isMarried: number;
    isActive: number;
    designationID: number=0;
    designation: string='';
 }
 export class Designation {
    id:number=0;
    designation:string='';
  }

Goto tsconfig.json file

Paste the below code in compilerOptions object

"strictPropertyInitialization": false,

Step 11- Create Employee Service Class for http operations

Run this command in terminal window

ng g s shared/Employee
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Designation, Epmloyee } from './epmloyee.model';
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  constructor(private myhttp:HttpClient) { }
  employeeUrl:string='https://localhost:44372/api/Employee';
  designationUrl:string='https://localhost:44372/api/Designation';
  listEmployee:Epmloyee[]=[]; //For Getting Data EmployeeList
  listDesignation:Designation[]=[];
  employeeData:Epmloyee=new Epmloyee(); //for post data / Insert data
  saveEmployee()
  {
    return this.myhttp.post(this.employeeUrl,this.employeeData);
  }
  updateEmployee()
  {
    return this.myhttp.put(`${this.employeeUrl}/${this.employeeData.id}` ,this.employeeData);
  }
  getEmployees():Observable<Epmloyee[]>
  {
    return this.myhttp.get<Epmloyee[]>(this.employeeUrl);
  }
  getDesignations():Observable<Designation[]>
  {
    return this.myhttp.get<Designation[]>(this.designationUrl);
  }
  deleteEmployee(id:number)
  {
    return this.myhttp.delete(`${this.employeeUrl}/${id}`);
  }
 }
!One Important point

Run your api project and copy url from your browser otherwise app can not connected with api.


Step 12- Install ngx-toastr

Full reference click this link Ngx-Toastr

Run below commands in terminal window

  • npm install ngx-toastr --save
  • npm install @angular/animations --save

Then goto src > style.css global css file and paste that code there

@import '~ngx-toastr/toastr';

Step 13- Add Components

Run below commands in terminal window

  • ng g c employee-details
  • ng g c employee-details/employee-form

Step 14- Uptade app.module.ts file

Compare your app.module.ts file with my app.module.ts file if there is something missing please update accordingly.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule} from '@angular/common/http';
import { EmployeeDetailsComponent } from './employee-details/employee-details.component';
import { EmployeeFormComponent } from './employee-details/employee-form/employee-form.component';
import { FormsModule } from '@angular/forms';
import{DatePipe} from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
  declarations: [
    AppComponent,
    EmployeeDetailsComponent,
    EmployeeFormComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot()
  ],
  providers: [DatePipe],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 15- Uptade index.html file

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Int</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
 </head>
 <body>
  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"    crossorigin="anonymous"></script>
 </body>
 </html>

Step 16- Start Work On employee-details Component

employee-details.component shows the list of registered employees.

First we work on employee-details.component.html file.

<div class="container">
<app-employee-form></app-employee-form>
</div>
<table class="table table-hover">
    <thead class="thead-dark">
     <tr>
      <th>Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Date of Join</th>
      <th>Designation</th>
      <th>Age</th>
      <th>Actions</th>
     </tr>
    </thead>
    <tbody>
      <tr *ngFor="let emp of empService.listEmployee"> 
        <td>{{emp.name}}</td>
        <td>{{emp.lastName}}</td>
        <td>{{emp.email}}</td>
        <td>{{emp.doj | date:'yyyy-MM-dd' }}</td>
        <td>{{emp.designation}}</td>
        <td>{{emp.age}}</td>
        <td>
          <div class="dropdown">
              <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
               Actions
              </button>
              <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                <a class="dropdown-item" href="#" (click)="populateEmployee(emp)">Edit</a>
                <a class="dropdown-item" href="#" (click)="delete(emp.id)">Delete</a>
                
              </div>
            </div>
        </td>
      </tr>
    </tbody>
</table>
Then we will work on employee-details.component.ts file.
import { DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { EmployeeService } from '../shared/employee.service';
import { Epmloyee } from '../shared/epmloyee.model';
import { EmployeeFormComponent } from './employee-form/employee-form.component';
@Component({
  selector: 'app-employee-details',
  templateUrl: './employee-details.component.html',
  styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {
  constructor(public empService:EmployeeService, public datepipe:DatePipe, public toast:ToastrService) { }
  @ViewChild(EmployeeFormComponent) emp:EmployeeFormComponent;
  ngOnInit() {
    this.empService.getEmployees().subscribe(data=>{
      this.empService.listEmployee=data;
    });
  }
  populateEmployee(selecetedEmployee:Epmloyee)
  {
    let df=this.datepipe.transform(selecetedEmployee.doj,'yyyy-MM-dd');
    selecetedEmployee.doj=df;
    this.empService.employeeData=selecetedEmployee;
    
    if(this.emp.isSlide==='off')
    {
     this.emp.hideShowSlide();
    }
  }
  delete(id:number)
  {
    if(confirm('Are you really want to delete this record?'))
    {
      this.empService.deleteEmployee(id).subscribe(data=> {
        this.empService.getEmployees().subscribe(data=>{
          this.empService.listEmployee=data;
          this.toast.error('Sucess','Record Deleted');
        });
      },
      err=>{
      });
    }
  }
 }
employee-form.component.html
<input #checkbox1 type="checkbox" name="toggle" id="toggle">
<label for="toggle"></label>
<div class="container">
</div>
<div class="formAdd">
    <form autocomplete="off" #myForm="ngForm" (ngSubmit)="myForm.form.valid && submit(myForm)">
        <div class="container">
            <div class="row">
                <div class="col-md-3">
                    <input type="hidden" name="id" [value]="empService.employeeData.id">

                    <label for="name" class="float-left">Name</label>
                    <div *ngIf="name.invalid && (name.touched || name.dirty)" class="float-right">
                        <p class="text-danger">Required</p>
                    </div>
                    <input type="text" name="name" class="form-control" placeholder="Enter Name" #name="ngModel" [(ngModel)]="empService.employeeData.name" required>
                </div>

                <div class="col-md-3">
                    <label for="name" class="float-left">Last Name</label>
                    <div *ngIf="lastname.invalid && (lastname.touched || lastname.dirty)" class="float-right">
                        <p class="text-danger">Required</p>
                    </div>
                    <input type="text" name="lastname" class="form-control" placeholder="Enter Last Name" #lastname="ngModel" [(ngModel)]="empService.employeeData.lastName" required>
                </div>

                <div class="col-md-3">
                    <label for="name" class="float-left">Email</label>
                    <div *ngIf="email.invalid && (email.touched || email.dirty)" class="float-right">
                        <p class="text-danger">Required</p>
                    </div>
                    <input type="Email" name="email" class="form-control" placeholder="Enter Email" #email="ngModel" [(ngModel)]="empService.employeeData.email" required>
                </div>

                <div class="col-md-3">
                    <label for="name" class="float-left">Age</label>
                    <div *ngIf="age.invalid && (age.touched || age.dirty)" class="float-right">
                        <p class="text-danger">Required</p>
                    </div>
                    <input type="number" name="age" class="form-control" placeholder="Enter Age" #age="ngModel" [(ngModel)]="empService.employeeData.age" required>
                </div>
            </div>

            <div class="row">
                <div class="col-md-3">
                    <label for="date" class="label float-left">Date of joining</label>
                    <div *ngIf="doj.invalid && (doj.touched || doj.dirty)" class="float-right">
                        <p class="text-danger">Required</p>
                    </div>
                    <input type="date" class="form-control" name="doj" [(ngModel)]="empService.employeeData.doj" #doj="ngModel" required>
                </div>


                <div class="col-md-3">
                    <label for="designation" class="label float-left">Designation</label>
                    <div *ngIf="designationID.touched && designationID.value===0" class="float-right">
                        <p class="text-danger">Required</p>
                    </div>
                    
                    <select name="designationID" class="form-control" #designationID="ngModel" [(ngModel)]="empService.employeeData.designationID" required>
                        <option value="0">Please Select</option>
                        <option  *ngFor="let desg of empService.listDesignation" [ngValue]="desg.id">{{ desg.designation }}</option>
                    </select>
                
                </div>

                <div class="col-md-6">
                    <label for="gender">Gender</label>
                    <div class="row">
                        <div class="col-md-6">
                            
                            <div class="form-check-inline">
                                <label class="form-check-label">
                                  <input type="radio" checked="true" id="rbtn" class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="empService.employeeData.gender" value="male">Male
                                </label>
                            </div>
                              
                              <div class="form-check-inline">
                                <label class="form-check-label">
                                  <input type="radio" id="rbtn" class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="empService.employeeData.gender" value="female">Female
                                </label>
                              </div>

                              <div class="form-check-inline">
                                <label class="form-check-label">
                                  <input type="radio" id="rbtn" class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="empService.employeeData.gender" value="others">Others
                                </label>
                              </div>
                              
                        </div>

                        <div class="col-md-6">
                            <div class="form-check-inline">
                                <label class="form-check-label">
                                    <input type="checkbox" class="form-check-input" name="isMarried" #isMarried="ngModel" [(ngModel)]="empService.employeeData.isMarried">Married
                                 </label>
                            </div>
                            <div class="form-check-inline">
                                <label class="form-check-label">
                                    <input type="checkbox" class="form-check-input" name="isActive" #isActive="ngModel" [(ngModel)]="empService.employeeData.isActive">Active
                                 </label>
                            </div>
                        </div>
                    </div>
                </div>

                
            </div>

            <div class="row">
                <div class="col-md-8"></div>
                <div class="col-md-2">
                    <button type="submit" [disabled]="designationID.value===0" class="btn btn-success btn-block">Save</button>
                </div>
                <div class="col-md-2">
                    <button type="reset" class="btn btn-danger btn-block">Cancel</button>
                </div>
            </div>


        </div>
    </form>
 </div>
Let's update employee-form.component.css

For sliding animated employee form we need to add some custom css

.formAdd {
  background:#c7b29e;
  color:#FFF;
  position: absolute;
  top: -250px;
  left: 0;
  width: 100%;
  height: 250px;
  padding: 20px;
  transition: top 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
  overflow: hidden;
  box-sizing: border-box;
  }
  #toggle {
    position:absolute;
    appearance:none;
    cursor:pointer;
    left:-100%;
    top:-100%;
  }
  #toggle + label {
    position:absolute;
    cursor:pointer;
    padding:10px;
    background: #26ae90;
    width: 100px;
    border-radius: 3px;
    padding: 8px 10px;
    color: #FFF;
    line-height:20px;
    font-size:12px;
    text-align:center;
    -webkit-font-smoothing: antialiased;
    cursor: pointer;
    margin:20px 50px;
    transition:all 500ms ease;
    }
    #toggle + label:after {
      content:"Add New" 
    }
    .container {
    transition: margin 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
      padding:2em 3em;
    }
    #toggle:checked ~ .formAdd {
      top: 0;
    }
    #toggle:checked ~ .container {
      margin-top: 250px;
    }
    #toggle:checked + label {
      background:#dd6149;
    }
    #toggle:checked + label:after {
      content:"Close"
    }
employee-form.component.ts
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { EmployeeService } from 'src/app/shared/employee.service';
import { Epmloyee } from 'src/app/shared/epmloyee.model';
 @Component({
  selector: 'app-employee-form',
  templateUrl: './employee-form.component.html',
  styleUrls: ['./employee-form.component.css']
 })
 export class EmployeeFormComponent implements OnInit {
  constructor(public empService:EmployeeService, public toast:ToastrService) { }
  @ViewChild('checkbox1') checkBox:ElementRef;
  isSlide:string='off';
  ngOnInit() {
    this.empService.getDesignations().subscribe(data=> {
        this.empService.listDesignation=data;
    });
  }
  submit(form:NgForm)
  {
    this.empService.employeeData.isMarried=form.value.isMarried==true?1:0;
    this.empService.employeeData.isActive=form.value.isActive==true?1:0;
    if(this.empService.employeeData.id==0)
      this.insertEmployee(form);
     else
     this.updateEployee(form);
  }
  insertEmployee(myform:NgForm)
  {  this.empService.saveEmployee().subscribe(d=> {
     this.resetForm(myform);
     this.refereshData();
     this.toast.success('Sucess','Record Saved');
    });
  }
  updateEployee(myform:NgForm)
  {
    this.empService.updateEmployee().subscribe(d=> {
      this.resetForm(myform);
      this.refereshData();
      this.toast.warning('Sucess','Record Updated');
    });
  }
  resetForm(myform:NgForm)
  {
    myform.form.reset(myform.value);
    this.empService.employeeData=new Epmloyee();
    this.hideShowSlide();
  }
  refereshData()
  {
    this.empService.getEmployees().subscribe(res=>{
      this.empService.listEmployee=res;
    });
  }
  hideShowSlide()
  {
    if(this.checkBox.nativeElement.checked)
    {
      this.checkBox.nativeElement.checked=false;
      this.isSlide='off';
    }
    else
    {
      this.checkBox.nativeElement.checked=true;
      this.isSlide='on';
    }
  }
 }

Step 17- Update app.component.html file

 <div class="container">
  <app-employee-details></app-employee-details>
  </div>
  <router-outlet></router-outlet>

❤️ Thank you for your time
If you like it so Please Like Share & subscribe Our Channel.
If you feel any problem please leave a comment
#DotNetCore #Angular13 #DotNetCoreWebApi #Logictycoon #Programming #learning #EntityFramework #WebApi #EFCore #.net6 #crud #angular #nodejs

Post a Comment

2 Comments

  1. Great work it is very help full.
    please create video master with detail crud in asp.net core web api and angular.

    ReplyDelete
  2. Gender is not getting when I clicked the Action --> Edit button. May I know where is the mistake? From Backend I already checked, and it is getting but in frontend it is not loaded.

    ReplyDelete