Skip to main content

Angular 14 CRUD Operation with Web API .Net 6.0

How to Perform CRUD Operation Using Angular 14


In this article, we will learn the angular crud (create, read, update, delete) tutorial with ASP.NET Core 6 web API. We will use the SQL Server database and responsive user interface for our Web app, we will use the Bootstrap 5.

Let's start step by step.

Step 1 - Create Database and Web API

First we need to create Employee database in SQL Server and web API to communicate with database. so you can use my previous article CRUD operations in web API using net 6.0 to create web API step by step.


As you can see, after creating all the required API and database, our API creation part is completed.

Now we have to do the angular part like installing angular CLI, creating angular 14 project, command for building and running angular application...etc.

Step 2 - Install Angular CLI

Now we have to install angular CLI into our system. If you have already installed angular CLI into your system then skip this step. 

To install angular CLI open visual studio code then go to Terminal menu -> New Terminal and copy and paste following command, and press enter.

npm install - g @angular/CLI

 

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

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

Step 3 - Create Angular Project

Now, we have to create a new angular project.

Before create angular project, we have to set directory path in Terminal window where you want to save your project like following.
 

Here, We'll save our project in E:\test folder, so we have write cd E:/test in the terminal window and hit enter.

To, Create a new angular project open the Terminal in visual studio code and write the following command, and hit enter.

ng new AngularEmpCRUD

Here, AngularEmpCRUD is the name of your Angular project.

After successfully created angular project, write cd AngularEmpCRUD to set project directory where our angular project is created.

cd AngularEmpCRUD

Now install bootstrap and bootstrap-icons packages from npm using following commands.

npm install bootstrap
npm install bootstrap-icons
npm install @popperjs/core

After installing packages package.json file look like as below.


{
  "name": "angular-emp-crud",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^14.1.0",
    "@angular/common": "^14.1.0",
    "@angular/compiler": "^14.1.0",
    "@angular/core": "^14.1.0",
    "@angular/forms": "^14.1.0",
    "@angular/platform-browser": "^14.1.0",
    "@angular/platform-browser-dynamic": "^14.1.0",
    "@angular/router": "^14.1.0",
    "@popperjs/core": "^2.11.5",
    "bootstrap": "^5.2.0",
    "bootstrap-icons": "^1.9.1",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.1.0",
    "@angular/cli": "~14.1.0",
    "@angular/compiler-cli": "^14.1.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.2.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.2"
  }
}

Step 4 - Create Class

Now we have to create class model. For that first we'll create folder _models inside app folder.

ng g class _models/emp

Now, we will write all the required properties of employees as shown below in the created class.

export class Emp {
    empId!: number;
    firstName!: string;
    lastName!: string;
    email!: string;
    phoneNumber!: string;
}

Step 5 - Create Service

Now we have to create service to call the web API. For that first we'll create folder _services inside app folder.

Now we'll create emp.service.ts files inside corresponding folder using following command.

ng g service _services/emp

Now, we will write insert, update, delete and read API function in the emp.service.ts service file as shown below.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { environment } from '../../environments/environment';
import { Emp } from '../_models/emp';

const baseUrl = environment.apiUrl + "/employee";

@Injectable({
  providedIn: 'root'
})
export class EmpService {

  constructor(private http: HttpClient) { }

 httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      "Access-Control-Allow-Origin": "*"
    }), responseType: 'text' as 'json'
  };

  getAll() {
    return this.http.get<Emp[]>(baseUrl);
  }

  getById(id: number) {
    return this.http.get<Emp>(`${baseUrl}/${id}`);
  }

  create(params: any) {
    return this.http.post(baseUrl, params, this.httpOptions);
  }

  update(params: any) {
    return this.http.put(`${baseUrl}`, params, this.httpOptions);
  }

  delete(id: number) {
    return this.http.delete(`${baseUrl}/${id}`,this.httpOptions);
  }
}

Step 6 - Setup Environment API

Now, we need to add our API base url in the environment.ts file as shown below.

// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.

export const environment = {
  production: false,
  apiUrl: 'http://localhost:7077/api'
};

/*
 * For easier debugging in development mode, you can import the following file
 * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
 *
 * This import should be commented out in production mode because it will have a negative impact
 * on performance if an error is thrown.
 */
// import 'zone.js/plugins/zone-error';  // Included with Angular CLI.

Step 7 - Create List Component

Now create employee folder inside app folder and create employee list component to display all the list of employees from database using following command.

ng g c employee/list --flat

After creating the list component, copy and past following code inside list.component.html file.


<section>
    <div class="card shadow my-2">
        <div class="card-header">
            <div class="row flex-between-center">
                <div class="col-md-4 d-flex align-items-center pe-0">
                    <h5 class="mb-0 text-nowrap py-2 py-xl-0">Employee List</h5>
                </div>
                <div class="col-md-8 ms-auto text-end ps-0">
                    <h6>Total : {{totalrow}}</h6>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped table-hover mb-0">
                    <thead>
                        <tr>
                            <th>FirstName</th>
                            <th>LastName</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let emp of employees">
                            <td>{{emp.firstName}}</td>
                            <td>{{emp.lastName}}</td>
                            <td>{{emp.email}}</td>
                            <td>{{emp.phoneNumber}}</td>
                            <td class="white-space-nowrap">
                                <a routerLink="/employee/edit/{{emp.empId}}" class="btn btn-outline-success" placement="bottom" ngbTooltip="Edit"><i
                                        class="bi bi-pencil"></i></a>
                                <button (click)="delete(emp)" class="btn btn-outline-danger" placement="bottom" ngbTooltip="Delete"><i
                                        class="bi bi-trash"></i></button>
                            </td>
                        </tr>
                        <tr *ngIf="totalrow===0">
                            <td colspan="5">
                                <div class="alert alert-danger">Employee not found</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>

<footer class="border-top text-muted fixed-bottom p-2">
    <div class="container text-center">
        <a routerLink="/employee/add" class="btn btn-success">
            <i class="bi bi-plus"></i>
        </a>
    </div>
</footer>

Now, you have to write following code inside list.component.ts file


import { Component, OnInit } from '@angular/core';

import { EmpService } from '../_services/emp.service';
import { Emp } from '../_models/emp';
import { first } from 'rxjs';

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

  employees!: Emp[];
  totalrow: number = 0;

  constructor(private empService: EmpService,) { }

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

  loadEmployee() {
    this.empService.getAll().pipe(first())
      .subscribe(d => {
        this.employees = d;
        this.totalrow = d.length;
      });
  }

  delete(emp: Emp) {
    this.empService.delete(emp.empId).pipe(first())
      .subscribe(() => {
        this.loadEmployee();
      })
  }
}

Now, you have write following code inside app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ListComponent } from './employee/list.component';


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

Now, you have to write following html code inside app.component.html file.


<!-- nav -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top">
  <div class="container-fluid">
    <a class="navbar-brand text-white" href="/">Employee Management</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
      aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item dropdown">
          <a class="nav-link" routerLink="/" role="button">
            Employees
          </a>
        </li>
      </ul>
    </div>
  </div>
</nav>

<!-- main app container -->
<div class="app-container container-fluid">
  <router-outlet></router-outlet>
</div>

Step 8 - Create Routing

Now, you have to mapping route with component inside app-routing.module.ts file as shown below.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ListComponent } from './employee/list.component';
import { AddeditComponent } from './employee/addedit.component';

const routes: Routes = [
  { path: '', component: ListComponent },
  { path: 'employee/add', component: AddeditComponent },
  { path: 'employee/edit/:id', component: AddeditComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 9 - Create Add/Edit Component

Now, create component for add and edit employee detail using following command.

ng g c employee/addedit --flat

After created addedit component, you have to write following code inside addedit.component.html file.

<section>
    <div class="row d-flex justify-content-center">
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h4>{{title}}</h4>
                </div>
                <div class="card-body">
                    <form [formGroup]="formadd" (ngSubmit)="onSubmit()">
                        <div class="row">
                            <div class="form-group mb-3">
                                <label class="mb-2">FirstName</label>
                                <input type="text" formControlName="firstName" class="form-control"
                                    [ngClass]="{ 'is-invalid': submitted && f['firstName'].errors }" />
                                <div *ngIf="submitted && f['firstName'].errors" class="invalid-feedback">
                                    <div *ngIf="f['firstName'].errors">FirstName is required</div>
                                </div>
                            </div>
                            <div class="form-group mb-3">
                                <label class="mb-2">LastName</label>
                                <input type="text" formControlName="lastName" class="form-control"
                                    [ngClass]="{ 'is-invalid': submitted && f['lastName'].errors }" />
                                <div *ngIf="submitted && f['lastName'].errors" class="invalid-feedback">
                                    <div *ngIf="f['lastName'].errors">LastName is required</div>
                                </div>
                            </div>
                            <div class="form-group mb-3">
                                <label class="mb-2">Email</label>
                                <input type="text" formControlName="email" class="form-control"
                                    [ngClass]="{ 'is-invalid': submitted && f['email'].errors }" />
                                <div *ngIf="submitted && f['email'].errors" class="invalid-feedback">
                                    <div *ngIf="f['email'].errors">Email is required</div>
                                </div>
                            </div>
                            <div class="form-group mb-3">
                                <label class="mb-2">Phone Number</label>
                                <input type="text" formControlName="phoneNumber" class="form-control"
                                    [ngClass]="{ 'is-invalid': submitted && f['phoneNumber'].errors }" />
                                <div *ngIf="submitted && f['phoneNumber'].errors" class="invalid-feedback">
                                    <div *ngIf="f['phoneNumber'].errors">Phone is required</div>
                                </div>
                            </div>
                        </div>

                        <button [disabled]="loading" type="submit" class="btn btn-success me-3">{{btnText}}</button>
                        <button type="button" class="btn btn-outline-danger" (click)="btnCancel()">Cancel</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

Now, you have to write following code inside addedit.component.ts file.


import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { EmpService } from '../_services/emp.service';

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

  formadd!: FormGroup;
  id!: number;
  loading = false;
  submitted = false;
  btnText: string = "Save";
  title: string = "New Employee";

  constructor(
    private formBuilder: FormBuilder,
    private empService: EmpService,
    private router: Router,
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.params['id'];

    if (this.id > 0) {
      this.loadData();
      this.btnText = "Update";
      this.title = "Edit Employee";
    }

    this.formadd = this.formBuilder.group({
      empId: 0,
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.required],
      phoneNumber: ['', Validators.required]
    });
  }

  // convenience getter for easy access to form fields
  get f() { return this.formadd.controls; }

  loadData() {
    this.empService.getById(this.id).subscribe(x => this.formadd.patchValue(x))
  }

  onSubmit() {

    this.submitted = true;

    // stop here if form is invalid
    if (this.formadd.invalid) {
      return;
    }

    this.loading = true;

    if (this.id > 0) {
      this.empService.update(this.formadd.value)
        .subscribe(
          data => {
            this.btnCancel();
          })
    }
    else {
      this.empService.create(this.formadd.value)
        .subscribe(
          data => {
            this.btnCancel();
          });
    }
  }

  btnCancel() {
    this.router.navigate([''])
  }
}

Step 10 - Add a CSS

Now in this step, we will add our custom CSS file inside assets folder as shown below.


:root {
    --table-color: seagreen;
    /*#588c7e*/
}

body {
    background-color: #eee;
    font-size: 14px;
    font-family: poppins;
}

.bg-theme {
    background-color: #006699 !important;
}

.navbar {
    background-color: #006699 !important;
}

.navbar-nav .nav-link {
    color: white !important;
}

.navbar-light .navbar-brand {
    color: white;
    font-weight: bold;
}

section {
    padding-top: 4rem;
    padding-bottom: 4rem;
}

h5,
.h5 {
    font-size: 1.2rem;
}

h6,
.h6 {
    font-size: 0.8333333333rem;
}

.form-group label {
    color: royalblue !important;
}

.card {
    border: none;
}

.card-header {
    padding: 1rem 1.25rem;
    background-color: white;
    border: none;
}

.table-fixed {
    overflow-y: auto;
    max-height: calc(100vh - 220px);
}

.table-fixed thead {
    position: sticky;
    top: 0;
}

.table thead {
    background-color: var(--table-color);
}

.table thead tr th {
    padding-top: 8px !important;
    padding-bottom: 8px !important;
    padding-left: 1.25rem;
    color: white;
    font-weight: 500;
}

.table tbody tr td {
    padding-top: 5px !important;
    padding-bottom: 5px !important;
    padding-left: 1.25rem;
    vertical-align: middle;
}

.table tbody tr td .btn,
.table ul li .btn {
    padding: 6px 10px;
    /*box-shadow: 0 5px 11px 0 rgba(0,0,0,.18),0 4px 15px 0 rgba(0,0,0,.15);*/
    margin-right: 0.5em;
}

.table tfoot>tr>th:first-child,
.table thead>tr>th:first-child,
.table tr th:first-child,
.table tr td:first-child {
    padding-left: 1.25rem;
}

.table tfoot>tr>th:last-child,
.table thead>tr>th:last-child,
.table tr th:last-child,
.table tr td:last-child {
    padding-right: 1.25rem;
}

.table-striped>tbody>tr:nth-of-type(2n)>* {
    --bs-table-accent-bg: var(--bs-table-striped-bg);
}

.table-striped>tbody>tr:nth-of-type(2n+1)>* {
    --bs-table-accent-bg: transparent;
}

.white-space-nowrap {
    width: 1px;
    white-space: nowrap;
}

footer {
    background-color: #454545 !important;
}

footer .btn {
    font-size: 14px !important;
    margin: 2px;
}

Now, we need to import bootstrap css and our custom css file inside styles.css file as shown below.


/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.css";
@import "~bootstrap-icons/font/bootstrap-icons.css";

@import "./assets/custom.css";

Step 11 - Run Project

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.

To run an angular project write following command.

ng serve

Your angular project will run on the URL http://localhost:4200/. After you access that url output will look like as below.

Please leave your comments and share a link of this article if you like. Thank you for reading this article.

Comments