Angular CRUD Example


Download Angular-CRUD Example

In this tutorial, we are going to learn how to build a CRUD application in Angular 14. CRUD operations stands for the four functions create, read, update, and delete in computer programming. Firstly we create API that fetch data from SQL Server table. Use that API in angular project to add, read, update and delete data. We will create a employee list on that list we can add new employee, update employee and delete employee. So this tutorial explains all the CRUD operations step by step. Here, we have divided the task mainly in 3 parts as following:

  1. SQL Server
  2. .NET API
  3. Angular 14

Part 1: SQL Server

Open SQL Server Management Studio, create a database named EmployeeDB and in this database create a table. Give that table a name like Employees. The below script to create Employees table.

USE [EmployeeDB]
GO

/****** Object: Table [dbo].[Employees] Script Date: 05-12-2022 00:40:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employees](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EmployeeType] [int] NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Designation] [nvarchar](max) NOT NULL,
[Salary] [int] NOT NULL,
CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Part 2: .NET API

Open Visual Studio and create a new project.

Angular API SQL Server

Now Click on the next button and give project name EmployeeResgistration.

Angular API SQL Server

Now click on the Next button and select API looks like as:

Angular API SQL Server

Now click on the create button. Project structure looks like:

Angular API SQL Server

Now open Web.Config file and add connection string inside connectionStrings section.

<add name="EmployeeDb" connectionString="Server=DESKTOP-G82VNVU;Initial Catalog=EmployeeDB; Persist Security Info=True; Integrated Security=True" providerName="System.Data.SqlClient" />

Now Add a employeeContext file and add the following code inside it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ResgistrationEmployee.Models;

namespace ResgistrationEmployee
{
    public class EmployeeContext : DbContext
    {
        private object _dsDbContext;

        public EmployeeContext() : base("EmployeeDb")
        {

        }
        public DbSet Employees { get; set; }
    }
}

Now create a employee controller and add the following code to the controller.

using EmployeeResgistration.Models;
using Microsoft.AspNetCore.Cors;
using ResgistrationEmployee;
using ResgistrationEmployee.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace EmployeeResgistration.Controllers
{
    [Route("api/employee")]
    public class EmployeeController : ApiController
    {
        EmployeeContext _dbContext = new EmployeeContext();

        [HttpGet]
        public IEnumerable GetAllEmployees()
        {
            return _dbContext.Employees.ToList();
        }

        [HttpGet]
        public Employee GetEmployeesbyid(int id)
        {
            return _dbContext.Employees.First(x => x.Id == id); 
        }

        [HttpPost]
        public IHttpActionResult Post(Employee employee)
        {
            try
            {
                _dbContext.Employees.Add(employee);
                _dbContext.SaveChanges();
                return Ok(new { Message =""});
            }
            catch (Exception ex)
            {

                return BadRequest();
            }

        }

        [HttpDelete]
        public IHttpActionResult Delete(int id)
        {
            try
            {
                var details = _dbContext.Employees.FirstOrDefault(x => x.Id == id);
                _dbContext.Employees.Remove(details);
                _dbContext.SaveChanges();
                return Ok();
            }
            catch (Exception)
            {

                return BadRequest();
            }

        }
        [HttpPut]
        public IHttpActionResult Put( int id, Employee employee)
        {
            try
            {             
                    var details = _dbContext.Employees.FirstOrDefault(x => x.Id ==id);
                    details.Designation = employee.Designation;
                    details.EmployeeType = employee.EmployeeType;
                    details.Salary = employee.Salary;
                    details.Name = employee.Name;
                    _dbContext.SaveChanges();
                
                return Ok();
            }
            catch (Exception)
            {

                return BadRequest();
            }

        }
    }
}

Now run the API application and will see GET, POST, DELETE and PUT API now running.

Angular API SQL Server

Part 3: Angular

1. Create an Angular application

The following command uses the Angular CLI to create a Angular application. The application name in the following example is angularcrud.

ng new angularcrud

Adding components for routing

The following command uses the Angular CLI to create component one by one. The components name in the following example is create, edit, view.

ng generate component create
ng generate component edit
ng generate component view

Now we create a shared folder which have two .ts file named service.service.ts and employee-model.ts. The project strcture looks like that:

Image-Projectfile

After creating our components parts,Open the employee-model.ts file inside the shared folder and adding the following code.

  export class EmployeeModel {
    id: number=0
    employeeType: number=0
    name: string=""
    designation: string=""
    salary: number=0
}

Now adding the following code on service.service.ts to fetch data from API.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { EmployeeModel } from './employee-model';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ServiceService {

  constructor(private http: HttpClient) { }

  getEmployeeList() {
    return this.http.get(environment.baseUrl);
  }
  
  saveEmplopyeeDetails(id:any, formarr: any) {  
    console.log(formarr);
    return this.http.put(`${environment.baseUrl}/?id=${id}`, formarr);
  }

  deleteRecord(id:any) {
    return this.http.delete(`${environment.baseUrl}/?id=${id}`);
  }

  GetEmployeesbyid(id:any) {
    return this.http.get(`${environment.baseUrl}/?id=${id}`);
  }

  addformdata(form:EmployeeModel):Observable{
    return this.http.post(`${environment.baseUrl}`,form);
  };
}

Now add the following code on app-routing.module.ts file to rout all the components.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CreateComponent } from './create/create.component';
import{ViewComponent} from './view/view.component';
import{EditComponent} from './edit/edit.component';

const routes: Routes = [
  {path:"",redirectTo: '/view', pathMatch: 'full'},
  {path:"view",component:ViewComponent},
  {path:"add",component:CreateComponent}, 
  {path:'edit/:Id', component: EditComponent }  
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponent=[ViewComponent,CreateComponent, EditComponent];

Now add the following code on app.module.ts file to rout all the components.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule,routingComponent } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
import { ViewComponent } from './view/view.component';
import { EditComponent } from './edit/edit.component';

@NgModule({
  declarations: [
    AppComponent,
    routingComponent,
    ViewComponent,
    EditComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now add the following code on create.component.html component file.


<div class="container" style="text-align: center;">
<p style="background-color: blue; color: white; text-align: center;">Add Employee</p>

<form [formGroup]="form" (ngSubmit)="onSubmit()"> 
<br>
<br>
<div class="form-group">
<div> 
<label>Select Employee Type</label> 
<select formControlName="employeeType">
<option value="">---Select Employee Type---</option>
<option value="1">Permanent</option>
<option value="2">Contract</option>
</select>
</div> 
</div>
<br>
<div class="form-group">
<div> 
<label style="padding-left: 31px;" > Employee Name</label> 
<input type="text" name="name" formControlName="name" placeholder="Enter Name"> 
<div *ngIf="f['name'].touched && f['name'].invalid" class="alert alert-danger">
<div *ngIf="f['name'].errors && f['name'].errors['required']">Title is required.</div>
</div> 
</div>
</div> <br>
<div class="form-group">
<div> <label> Employee Designation</label> 
<input type="text" name="designation" formControlName="designation" placeholder="Enter Designation"> 
<div *ngIf="f['designation'].touched && f['designation'].invalid" class="alert alert-danger">
<div *ngIf="f['designation'].errors && f['designation'].errors['required']">Designation is required.</div>
</div> 
</div>
</div> <br>
<div class="form-group">
<div> <label style="padding-left: 31px;"> Employee salary</label> 
<input type="text" name="salary" formControlName="salary" placeholder="Enter Salary"> 
<div *ngIf="f['salary'].touched && f['salary'].invalid" class="alert alert-danger">
<div *ngIf="f['salary'].errors && f['salary'].errors['required']">Salary is required.</div>
</div> 
</div>
</div><br><br>
<button style="margin-left: 100px;" type="submit" [disabled]="!form.valid">Submit</button> 
</form>
</div>

Now add the following code on create.component.ts component file.

import { Component, OnInit } from '@angular/core';
import { FormBuilder,FormControl, FormGroup, Validators } from '@angular/forms';
import { ServiceService } from '../shared/service.service';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  form!: FormGroup;
  empList: any;
  constructor(private _service: ServiceService,
    private fb: FormBuilder
  ){ }
  
  ngOnInit(): void {
    this.form =  new FormGroup({
      id: new FormControl('0', [Validators.required]),
      employeeType:new FormControl('', [Validators.required]),
      name: new FormControl('', [Validators.required]),
      designation: new FormControl('', [Validators.required]),
      salary:new FormControl('', [Validators.required]),
    });
  }
  get f(){
    return this.form.controls;
  }

  onSubmit() {
    this._service.addformdata(this.form.value).subscribe({
      next: () => {
        alert("data saved");
      },
      error: error => {}
    })
  }
}

Now add the following code on edit.component.html component file.

<div class="container" style="text-align: center;">
<p style="background-color: blue; color: white; text-align: center;">Update Employee</p>
<form [formGroup]="form" (ngSubmit)="onSubmit()"> 
<br>
<br> 
<div class="form-group">
<div> 
<label>Select Employee Type</label> 
<select formControlName="employeeType" ngValue="empList.EmployeeType" [(ngModel)]="empList.employeeType"> 
<option *ngFor="let objetype of Employeetype" value="objetype.id">{{objetype.name}}</option> 
</select>
</div> 
</div>
<br>
<div class="form-group">
<div> 
<label style="padding-left: 31px;" > Employee Name</label> 
<input type="text" name="name" [(ngModel)]="empList.Name" formControlName="name" placeholder="Enter Name"> 
<div *ngIf="f['name'].touched && f['name'].invalid" class="alert alert-danger">
<div *ngIf="f['name'].errors && f['name'].errors['required']">Title is required.</div>
</div> 
</div>
</div> <br>
<div class="form-group">
<div> <label> Employee Designation</label> 
<input type="text" name="designation" [(ngModel)]="empList.Designation" formControlName="designation" placeholder="Enter Designation"> 
<div *ngIf="f['designation'].touched && f['designation'].invalid" class="alert alert-danger">
<div *ngIf="f['designation'].errors && f['designation'].errors['required']">Designation is required.</div>
</div> 
</div>
</div> <br>
<div class="form-group">
<div> <label style="padding-left: 31px;"> Employee salary</label> 
<input type="text" name="salary" [(ngModel)]="empList.Salary" formControlName="salary" placeholder="Enter Salary"> 
<div *ngIf="f['salary'].touched && f['salary'].invalid" class="alert alert-danger">
<div *ngIf="f['salary'].errors && f['salary'].errors['required']">Salary is required.</div>
</div> 
</div>
</div><br><br>
<button style="margin-left: 100px;" type="submit">Update</button> 
</form>
</div>

Now add the following code on edit.component.ts component file.

import { Component, OnInit } from '@angular/core';
import { FormBuilder,FormControl, FormGroup, Validators } from '@angular/forms';
import { ServiceService } from '../shared/service.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {

  form!: FormGroup;
  empList: any;
  id!: number;

  constructor(private _service: ServiceService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router:Router
  ){ }
  
  ngOnInit(): void {
    this.id = this.route.snapshot.params['Id'];    
    this._service.GetEmployeesbyid(this.id).subscribe((data:any)=>{
      this.empList = data;
      console.log(this.empList);
  });


    this.form =  new FormGroup({
      id: new FormControl('0', [Validators.required]),
      employeeType:new FormControl('', [Validators.required]),
      name: new FormControl('', [Validators.required]),
      designation: new FormControl('', [Validators.required]),
      salary:new FormControl('', [Validators.required]),
    });     
}
Employeetype: any[] = [
  { id: 1, name: 'Permanent' },
  { id: 2, name: 'Contract' } 
];

get f(){
  return this.form.controls;
} 
  onSubmit() {   
    this._service.saveEmplopyeeDetails(this.id, this.form.value).subscribe((res:any) => {
        alert("Data Update");          
    })
  }
}

Now add the following code on view.component.html component file.

<div class="container">
<h1 style="background-color: blue; color: white; text-align: center;">Angular CRUD Example</h1>
<a href="#" [routerLink]="['/add/']" class="btn btn-success">Add Employee</a>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Employee Type</th>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
<th width="250px">Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let objview of tableview">
<td>{{ objview.Id }}</td>
<td>{{ objview.EmployeeType }}</td>
<td>{{ objview.Name }}</td>
<td>{{ objview.Designation }}</td>
<td>{{ objview.Salary }}</td> 
<td> 
<a href="#" [routerLink]="['/edit/', objview.Id]" class="btn btn-primary">Edit</a>
<button type="button" (click)="deleteEmployee(objview.Id)" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>

Now add the following code on view.component.ts component file.

import { Component, OnInit } from '@angular/core';
import { ServiceService } from '../shared/service.service';


@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {

  tableview:any = [];

  constructor( private _service: ServiceService) { 
   
  }

  ngOnInit(): void {
    this.getdata();
  }

  getdata() {
    this._service.getEmployeeList().subscribe((data :any)=>{
      this.tableview = data;
      console.log(this.tableview);
    })  
  }

  deleteEmployee(id:number){
    this._service.deleteRecord(id).subscribe(res => {        
         console.log('deleted successfully!');
    })
  }
}

Now run the web api project first and after that run the angular project. We will see the view coponent as we have set it default in routing.

  {path:"",redirectTo: '/view', pathMatch: 'full'},

We will see the the following records already stored in SQL Table Employees.

Angular API SQL Server

Now click on the Add Employee button to add new employee.

Angular API SQL Server

After adding new employee record name as sanjay. we will see table record with added new employee.

Angular API SQL Server

Now click on the table Edit button to update existing employee record.

Angular API SQL Server

Now we change name sanjay to sanjay kushwaha.

Angular API SQL Server

Now see the table with updated record.

Angular API SQL Server

Now click on delete button to delete record as named sanjay

Angular API SQL Server

Download Angular-CRUD Example


Prev Next