In this tutorial, we will create a simple Angular 17 CRUD application using local storage to store data.
Angular is a popular framework for building dynamic web applications. It provides a way to organize and structure your code in a modular way, making it easier to maintain and scale your application. Local storage is a web storage mechanism that allows data to be stored in the browser and retrieved at a later time.
For this tutorial, we will start by setting up a new Angular project using the Angular CLI. If you haven’t already installed the Angular CLI, you can do so by running the following command:
npm install -g @angular/cli
Next, create a new Angular project by running the following command:
ng new angular-crud-localstorage
Navigate to the project folder by running:
cd angular-crud-localstorage
Now that we have created our project, let’s create a new component for our CRUD operations. Run the following command to generate a new component:
ng generate component customer
This will create a new customer
folder within the src/app
directory, along with all the files necessary for the component.
Next, we will create a service to handle our CRUD operations. Run the following command to generate a new service:
ng generate service customer
This will create a new customer
folder within the src/app
directory, along with the necessary files for the service.
Now, let’s start by adding some basic functionality to our component. Open the customer.component.ts
file and add the following code:
import { Component, OnInit } from '@angular/core';
import { CustomerService } from '../customer.service';
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
customers: any[];
constructor(private customerService: CustomerService) { }
ngOnInit() {
this.customers = this.customerService.getCustomers();
}
addCustomer(name: string, age: number, email: string) {
this.customerService.addCustomer({ name, age, email });
this.customers = this.customerService.getCustomers();
}
updateCustomer(customer) {
this.customerService.updateCustomer(customer);
this.customers = this.customerService.getCustomers();
}
deleteCustomer(customer) {
this.customerService.deleteCustomer(customer);
this.customers = this.customerService.getCustomers();
}
}
In this code, we are importing the CustomerService
and using it to get, add, update, and delete customers. Next, open the customer.component.html
file and add the following code:
<div>
<h2>Customers</h2>
<ul>
<li *ngFor="let customer of customers">
{{ customer.name }} - {{ customer.age }} - {{ customer.email }}
<button (click)="updateCustomer(customer)">Update</button>
<button (click)="deleteCustomer(customer)">Delete</button>
</li>
</ul>
</div>
<div>
<h2>Add Customer</h2>
<input type="text" placeholder="Name" #name>
<input type="number" placeholder="Age" #age>
<input type="email" placeholder="Email" #email>
<button (click)="addCustomer(name.value, age.value, email.value)">Add Customer</button>
</div>
In this code, we are displaying a list of customers and providing an input form to add a new customer. We are also providing buttons to update and delete customers.
Next, let’s move on to defining the CRUD operations in the customer.service.ts
file. Open the customer.service.ts
file and add the following code:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CustomerService {
getCustomers(): any[] {
return JSON.parse(localStorage.getItem('customers')) || [];
}
addCustomer(customer) {
const customers = this.getCustomers();
customers.push(customer);
localStorage.setItem('customers', JSON.stringify(customers));
}
updateCustomer(updatedCustomer) {
const customers = this.getCustomers();
const index = customers.findIndex(c => c.email === updatedCustomer.email);
customers[index] = updatedCustomer;
localStorage.setItem('customers', JSON.stringify(customers));
}
deleteCustomer(customer) {
const customers = this.getCustomers();
const index = customers.findIndex(c => c.email === customer.email);
customers.splice(index, 1);
localStorage.setItem('customers', JSON.stringify(customers));
}
}
In this code, we are defining the getCustomers()
, addCustomer()
, updateCustomer()
, and deleteCustomer()
functions to handle our CRUD operations. These functions read from and write to the local storage to store and retrieve customer data.
Finally, we need to add the CustomerComponent
to the app.module.ts
file. Open the app.module.ts
file and add the following code:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomerComponent } from './customer/customer.component';
import { CustomerService } from './customer.service';
@NgModule({
declarations: [
AppComponent,
CustomerComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [CustomerService],
bootstrap: [AppComponent]
})
export class AppModule { }
Now, you can run the Angular application by running the following command:
ng serve
Open your browser and navigate to http://localhost:4200/
to see the CRUD application in action. You can add, update, and delete customers and the changes will be persisted in the local storage.
That’s it! You have successfully created a simple Angular 17 CRUD application using local storage. You can further enhance this application by adding validation, error handling, and styling to make it more robust and user-friendly.
I hope this tutorial was helpful in getting started with Angular 17 CRUD operations using local storage. Happy coding!
Sir can u provide the css
Thanks
🤩
This has many flaws, first of all the delete function only deletes the last item. secondly after deleting the ID is repeat for new entries hence making update function break. good tutorial but i wish logic was ecplained properly
Thank you very much for your nice explanations .
I am facing an issue while using local storage it says that local storage is not lteset
The best video of the world!!!
I noticed that when I press the delete button only the last item is deleted not the item which we require to be deleted. So, I made this change it worked
onDelete(item: Student) {
const isDelet = confirm('Are you sure want to Delete');
if (isDelet) {
const currentRecord = this.studentList.findIndex(
(m) => m.id === item.id
);
if (currentRecord !== -1) {
this.studentList.splice(currentRecord, 1);
localStorage.setItem('angular17crud', JSON.stringify(this.studentList));
}
}
}
Thank you for the video
Why don't u use Reactive form 😶
viewchild ka error nhi ja rha hai help me plz
thanks
Bro 15:45 touched me so much yeah like what you say try to write the code on my own this is really my weak point that make me struggle to learn i always copy without knowing what it useful
Sir, can you please show how to divide this one component into different components.
Could you please cover one vedio with validation part
Hello, good morning, I have followed the tutorial and I get an error in the part of the @viewChild('myModal') decorator, and I can't get rid of the error or remove it, I can't follow you. I'm sorry.
Thanks bro
Hello bro.
In code :
onEdit(item: Student) {
this.studentObj = item;
this.openModal();
}
"Referential Equality"
this.studentList will change when this.studentObj change
I think we have fix :
onEdit(item: Student) {
this.studentObj = { …item };
this.openModal();
}
Hello bro, Thanks for your video!
I have a question.
I don't see you install Bootstrap and Fontawesome. I tried cloning your repo and running in my local computer. An error occurred
angular:styles/global:styles:1:8:
✘ [ERROR] Could not resolve "./node_modules/bootstrap/dist/css/bootstrap.min.css"
✘ [ERROR] Could not resolve "./node_modules/@fortawesome/fontawesome-free/css/all.min.css"
Thanks. Have a good day
Sir, please marathimdhe suddha courses launch kara
Dear Chetan. A quick question/guidance! Do you have video on CRUD with Mock APIs for us to learn and practice? Would greatly appreciate if you can guide us.