Angular 18 CRUD Operations | angular crud example

Angular 18 CRUD Operations | angular crud example

Introduction

Local storage in Angular is a powerful tool for storing small amounts of data directly in the user's browser. This data persists even after the browser is closed, making it ideal for storing user preferences, application state, or small datasets. In this article,Angular 18 CRUD Operations we'll delve into how to perform CRUD (Create, Read, Update, Delete) operations on data stored in local storage using Angular 18 CRUD Operations.

Angular 18 CRUD Operations  angular crud example



step1: create new project > ng new Angular18CRUD

step2: create new component >ng g c home

step3: create class or interface > ng g class empDetails
when we creating class or interface create variable and datatype this object as follows.

#EmpDetails.ts

export class EmpDetails {
    empId: number;
    empName: string;
    empEmail: string;
    empAddress: string;
    empCity: string;
    empPin: string;

    constructor() {
        this.empId = 1;
        this.empName = "";
        this.empEmail = "";
        this.empAddress = "";
        this.empCity = "";
        this.empPin = '';

    }
}

step4: Design simple reactive form and data table for showing employee details in table list.

#home.component.html

<div class="container p-1">
    <div class="row">
        <div class="col-8">
            <div class="card">
                <div class="card-header bg-info">
                    Employee Details
                </div>
                <div class="card-body">

                    <div class="row">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>empId</th>
                                    <th>empName</th>
                                    <th>empEmail</th>
                                    <th>empAddress</th>
                                    <th>empCity</th>
                                    <th>empPin</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @for(item of EmpDetailsList; track $index){
                                <tr>
                                    <td>{{$index+1}}</td>
                                    <td>{{item.empName}}</td>
                                    <td>{{item.empEmail}}</td>
                                    <td>{{item.empAddress}}</td>
                                    <td>{{item.empCity}}</td>
                                    <td>{{item.empPin}}</td>
                                    <td class="text-center">
                                        <button class="btn btn-info" (click)="OnEdit(item)">Edit</button> &nbsp;
                                        <button class="btn btn-danger" (click)="OnDelete(item.empId)">Delete</button>
                                    </td>
                                </tr>
                                }

                            </tbody>

                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-4">
            <div class="card">
                <div class="card-header bg-warning">
                    Employee form
                </div>
                <div class="card-body">
                    <form [formGroup]="empolyeeForm">

                        <div class="row">

                            <div class="col-6">
                                <label>Employee Name</label>
                                <input type="text" class="form-control" formControlName="empName">
                                <div class="text-denger">
                                    @if(empolyeeForm.controls['empName'].touched){
                                    @if(empolyeeForm.controls['empName'].errors?.['required']){
                                    <span>Name is required</span>
                                    }
                                    }
                                </div>
                            </div>
                            <div class="col-6">
                                <label>Employee Email</label>
                                <input type="text" class="form-control" formControlName="empEmail">
                            </div>
                            <div class="col-6">
                                <label>Employee Address</label>
                                <input type="text" class="form-control" formControlName="empAddress">
                            </div>
                            <div class="col-6">
                                <label>Employee city</label>
                                <input type="text" class="form-control" formControlName="empCity">
                            </div>
                            <div class="col-6">
                                <label>City pin</label>
                                <input type="text" class="form-control" formControlName="empPin">
                                <div class="text-denger">
                                    @if(empolyeeForm.controls['empPin'].touched){
                                    @if(empolyeeForm.controls['empPin'].errors?.['minlength']){
                                    <span>Pin is required</span>
                                    }
                                    }
                                </div>
                            </div>

                            <div class="col-6">
                                <div class="row">
                                    <button type="button" class="btn btn-warning mt-2" (click)="reset()">Reset</button>
                                    @if(empolyeeForm.controls['empId'].value == '1'){
                                    <button class="btn btn-primary mt-2" (click)="SaveData()">Submit</button>
                                    }
                                    @else{
                                    <button class="btn btn-warning mt-2" (click)="UpdateData()">Update</button>
                                    }
                                </div>
                            </div>

                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

step5:

write code home.ts file first import reactiveFormModule and initialized  name to that form as follow.

#home.component.TS

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { EmpDetails } from './model/emp-details';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent {

  empolyeeForm!: FormGroup;
  empObject: EmpDetails = new EmpDetails();
  EmpDetailsList: EmpDetails[] = [];

  constructor() {
    this.createForm();
    const oldData = localStorage.getItem("EmpData");
    if (oldData != null) {
      const parseData = JSON.parse(oldData);
      this.EmpDetailsList = parseData;
    }
  }

  createForm() {
    this.empolyeeForm = new FormGroup({
      empId: new FormControl(this.empObject.empId),
      empName: new FormControl(this.empObject.empName, [Validators.required]),
      empEmail: new FormControl(this.empObject.empEmail),
      empAddress: new FormControl(this.empObject.empAddress),
      empCity: new FormControl(this.empObject.empCity),
      empPin: new FormControl(this.empObject.empPin, [Validators.minLength(6), Validators.required])
    });
  }

  SaveData() {

    const oldData = localStorage.getItem("EmpData");
    if (oldData != null) {
      const parseData = JSON.parse(oldData);
      this.empolyeeForm.controls['empId'].setValue(parseData.length + 1);
      this.EmpDetailsList.unshift(this.empolyeeForm.value);
    } else {
      this.EmpDetailsList.unshift(this.empolyeeForm.value);
    }
    localStorage.setItem("EmpData", JSON.stringify(this.EmpDetailsList))
    this.reset()
  }

  reset() {
    this.empObject = new EmpDetails();
    this.createForm();
  }

  OnEdit(item: EmpDetails) {
    this.empObject = item;
    this.createForm();
  }

  UpdateData() {
    const record = this.EmpDetailsList.find(m => m.empId == this.empolyeeForm.controls['empId'].value);
    if (record != undefined) {
      record.empName = this.empolyeeForm.controls['empName'].value;
      record.empAddress = this.empolyeeForm.controls['empAddress'].value;
      record.empEmail = this.empolyeeForm.controls['empEmail'].value;
    }
    localStorage.setItem("EmpData", JSON.stringify(this.EmpDetailsList));
    this.reset();

  }

  OnDelete(id: number) {

    const Delete = confirm("Are you Deleted");

    if (Delete) {
      const index = this.EmpDetailsList.findIndex(m => m.empId == id);
      this.EmpDetailsList.splice(index, 1);
      localStorage.setItem("EmpData", JSON.stringify(this.EmpDetailsList));
    }

  }

}


Conclusion

By following these steps, you've successfully implemented CRUD operations with local storage in your Angular 18 application. This approach provides a convenient way to store and manage small amounts of data locally, enhancing the user experience and functionality of your application.

FAQ

1.What is the full form of CRUD?
Ans- CRUD stands for Create, Read, Update, Delete. These are the four fundamental operations that are typically performed on data in a database or other data storage system. read more

2.What is REST API CRUD operations?
Ans-REST APIs (Representational State Transfer APIs) provide a standard way to interact with web services. CRUD (Create, Read, Update, Delete) operations are the fundamental actions performed on data through REST APIs.

Create: Adds new data to a resource.
Read: Retrieves existing data from a resource.
Update: Modifies existing data in a resource.
Delete: Removes data from a resource.
These operations typically correspond to HTTP methods: POST, GET, PUT/PATCH, and DELETE, respectively.

read more.





 

0 Comments