Angular CRUD | Angular local storage |CRUD Application with Local Storage in Angular
Introduction:
As an Angular developer, we are mostly familiar with building dynamic web applications. One of the common requirements for any interviewer is implementing CRUD (Create, Read, Update, Delete) operations. In this tutorial Angular crud, we are mostly creating a simple CRUD Application with Local Storage in Angular and storing data in the browser with local storage. This is a great way to persist data without needing a backend server.
We fallow all the steps at the end of this blog we all have a fully functional Angular crud Application with Local Storage in Angular crudto save and manage data as a developer.
Before we start applications, we know that the following things are needed:
-> Basic knowledge of Angular and TypeScript.
-> Node.js and npm installed on your machine.
-> Angular CLI installed (npm install -g @angular/cli).
Step 1: Set Up a New Angular Project
Create a new Angular project:
Open your terminal and run the following command to create a new Angular project:
> ng new angular-crud-localstorage
Choose CSS for styling and No for Angular routing (we won’t need it for this simple project).
Navigate to the project folder:
> cd angular-crud-localstorage
Start the development server:
> ng serve
Open your browser and navigate to http://localhost:4200 to see your app running.
Step 2: Create a Data Model
Generate a new interface:
Create a model to define the structure of the data to store.
Run the following command to generate a new interface:
> ng generate interface models/item
Define the Item interface:
Open the newly created src/app/models/item.ts file and define the interface:
export interface Item {
id: number;
name: string;
description: string;
}
Step 3: Create a Service to Handle CRUD Operations
Generate a new service:
Run the following command to create a service:
ng generate service services/localstorage
Implement Angular crud methods:
Open src/app/services/localstorage.service.ts and add the following code:
import { Injectable } from '@angular/core';
import { Item } from '../models/item';
@Injectable({
providedIn: 'root',
})
export class LocalstorageService {
private storageKey = 'crud-app-items';
constructor() {}
// Get all items
getItems(): Item[] {
const items = localStorage.getItem(this.storageKey);
return items ? JSON.parse(items) : [];
}
// Add a new item
addItem(item: Item): void {
const items = this.getItems();
items.push(item);
localStorage.setItem(this.storageKey, JSON.stringify(items));
}
// Update an item
updateItem(updatedItem: Item): void {
const items = this.getItems();
const index = items.findIndex((item) => item.id === updatedItem.id);
if (index !== -1) {
items[index] = updatedItem;
localStorage.setItem(this.storageKey, JSON.stringify(items));
}
}
// Delete an item
deleteItem(id: number): void {
const items = this.getItems().filter((item) => item.id !== id);
localStorage.setItem(this.storageKey, JSON.stringify(items));
}
// Generate a unique ID
generateId(): number {
const items = this.getItems();
return items.length > 0 ? Math.max(...items.map((item) => item.id)) + 1 : 1;
}
}
Step 4: Create Components for CRUD Operations
Generate components:
Run the following commands to generate components for listing, adding, and editing items:
ng generate component components/item-list
ng generate component components/item-form
Update item-list.component.ts:
Open src/app/components/item-list/item-list.component.ts and add the following code:
import { Component, OnInit } from '@angular/core';
import { LocalstorageService } from '../../services/localstorage.service';
import { Item } from '../../models/item';
@Component({
selector: 'app-item-list',
templateUrl: './item-list.component.html',
styleUrls: ['./item-list.component.css'],
})
export class ItemListComponent implements OnInit {
items: Item[] = [];
constructor(private localStorageService: LocalstorageService) {}
ngOnInit(): void {
this.loadItems();
}
loadItems(): void {
this.items = this.localStorageService.getItems();
}
deleteItem(id: number): void {
this.localStorageService.deleteItem(id);
this.loadItems();
}
}
Update item-list.component.html:
Open src/app/components/item-list/item-list.component.html and add the following code:
html
<h2>Item List</h2>
<ul>
<li *ngFor="let item of items">
{{ item.name }} - {{ item.description }}
<button (click)="deleteItem(item.id)">Delete</button>
</li>
</ul>
Update item-form.component.ts:
Open src/app/components/item-form/item-form.component.ts and add the following code:
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Item } from '../../models/item';
import { LocalstorageService } from '../../services/localstorage.service';
@Component({
selector: 'app-item-form',
templateUrl: './item-form.component.html',
styleUrls: ['./item-form.component.css'],
})
export class ItemFormComponent {
@Input() item: Item = { id: 0, name: '', description: '' };
@Output() formSubmit = new EventEmitter<Item>();
constructor(private localStorageService: LocalstorageService) {}
onSubmit(): void {
if (this.item.id === 0) {
this.item.id = this.localStorageService.generateId();
this.localStorageService.addItem(this.item);
} else {
this.localStorageService.updateItem(this.item);
}
this.formSubmit.emit(this.item);
}
}
Update item-form.component.html:
Open src/app/components/item-form/item-form.component.html and add the following code:
<h2>{{ item.id ? 'Edit Item' : 'Add Item' }}</h2>
<form (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input type="text" id="name" [(ngModel)]="item.name" name="name" required />
<label for="description">Description:</label>
<input type="text" id="description" [(ngModel)]="item.description" name="description" required />
<button type="submit">{{ item.id ? 'Update' : 'Add' }}</button>
</form>
Run HTML
Step 5: Update the App Component
Update app.component.ts:
Open src/app/app.component.ts and add the following code:
import { Component } from '@angular/core';
import { Item } from './models/item';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
selectedItem: Item = { id: 0, name: '', description: '' };
onItemSelect(item: Item): void {
this.selectedItem = { ...item };
}
onFormSubmit(): void {
this.selectedItem = { id: 0, name: '', description: '' };
}
}
Update app.component.html:
Open src/app/app.component.html and add the following code:
<h1>Angular CRUD with Local Storage</h1>
<app-item-form [item]="selectedItem" (formSubmit)="onFormSubmit()"></app-item-form>
<app-item-list (itemSelect)="onItemSelect($event)"></app-item-list>
Run HTML
Step 6: Test Your Application
Run the application:
> ng serve
Open your browser and navigate to http://localhost:4200.
--> yes, developer we done it Angular crud Application with Local Storage in Angular
You should be able to:
Add new items.
Edit existing items.
Delete items.
See the changes persist in local storage.
Conclusion
In this article through we can easily built a Angular crud Application with Local Storage in Angular. This project demonstrates how to manage data without a backend server, making it a great starting point for small-scale applications.
This is very nice to expand this project Angular crud by adding features like validation, sorting, or filtering.
Read More :
Keywords: #Angular_CRUD, #Angular_local_storage, #CRUD_operations

0 Comments