Building a CRUD Application in Angular

Building a CRUD Application in Angular with Reactive Forms and Local Storage

In this tutorial, we'll walk through the process of creating a simple CRUD (Create, Read, Update, Delete) application in Angular. We'll leverage Angular's reactive forms for user input and use local storage to persist data. This example is a great starting point for beginners and provides a foundation for more complex applications.

Prerequisites

Before we dive into the tutorial, make sure you have Angular installed. If not, you can install it globally using the following command:

    • npm install -g @angular/cli

Setting Up the Project

  1. Create a new Angular project using the Angular CLI:
      • ng new angular-crud-app cd angular-crud-app

Lets deep dive in the code :

  • C stands for Create ie we create the form 
  • R stands for Remove ie clear the entries in the form 
  • U stands for Update, which means we can modify the entries in the form or table, or database
  • D stands for Delete, which means to remove the entries from the database or table 
  1. Create operation syntax :
    • first, you have to create a table and form in app.component.html file as followes:-

<div class="container m-5 p-5"> <div class="row"> <!-- Form Section --> <div class="col-lg-4"> <form [formGroup]="loginForm"> <div class="mb-3 form-group"> <label for="exampleInputEmail1" class="form-label">Email address</label> <input class="form-control" formControlName="Email"> </div> <div class="mb-3 form-group"> <label for="exampleInputPassword1" class="form-label">Password</label> <input class="form-control" formControlName="Password"> </div> <div class="m-4 text-center"> <button type="button" class="btn btn-dark" (click)="clear()">Clear</button> <button type="button" class="btn btn-success" style="margin-left: 10px;" (click)="update()">Update</button> <button type="button" class="btn btn-success" style="margin-left: 10px;" (click)="submit()">Submit</button> </div> </form> </div> <!-- Table Section --> <div class="col-lg-8"> <table class="table table-striped"> <!-- Table Header --> <thead> <tr> <th scope="col">#</th> <th scope="col">Email</th> <th scope="col">Password</th> <th>Action</th> </tr> </thead> <!-- Table Body --> <tbody> <tr *ngFor="let l of loginList; let i = index"> <td>{{i+1}}</td> <td>{{l.Email}}</td> <td>{{l.Password}}</td> <td> <button type="button" class="btn btn-primary m-1" (click)="edit(i)">Edit</button> <button type="button" class="btn btn-danger m-1" (click)="delete(i)">Delete</button> </td> </tr> </tbody> </table> </div> </div> </div> <router-outlet></router-outlet>

    • output :-
    • Note: you have to use bootstrap to get the same output I have not mention the bootstrap link here
    • you can mention it in the index.html
    • app. comonent.ts

import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; export class AppComponent implements OnInit { // Reactive form for user login loginForm: FormGroup; // List to store login entries loginList: any = []; // Index to track the selected entry for editing index = ''; // Constructor to initialize the form constructor(private formbuilder: FormBuilder) { this.loginForm = this.formbuilder.group({ Email: [''], Password: [''], }); } // Lifecycle hook: OnInit ngOnInit(): void { // Retrieve data from local storage during component initialization let data = localStorage.getItem('loginList'); this.loginList = JSON.parse(data || ''); console.log('loginList', this.loginList); } // Method to handle form submission submit() { console.log(this.loginForm.value); // Add the current form values to loginList and store in local storage this.loginList.push(this.loginForm.value); localStorage.setItem('loginList', JSON.stringify(this.loginList)); // Clear the form this.clear(); } // Method to populate form for editing edit(i: any) { this.loginForm.patchValue({ Email: this.loginList[i].Email, Password: this.loginList[i].Password, }); // Update the index for tracking the selected entry this.index = i; } // Method to update the selected entry update() { // Update the selected entry with the modified form values this.loginList[this.index].Email = this.loginForm.value.Email; this.loginList[this.index].Password = this.loginForm.value.Password; // Update local storage and clear the form localStorage.setItem('loginList', JSON.stringify(this.loginList)); this.clear(); } // Method to reset the form clear() { this.loginForm.reset(); } // Method to delete the selected entry delete(i: any) { // Remove the selected entry from loginList and update local storage this.loginList.splice(i, 1); localStorage.setItem('loginList', JSON.stringify(this.loginList)); } }

  • this code is used to make form and table work, you have to mention it in your (.ts) file
  • I have included a reactive form with local Storage here !!

Q&A Section

Q1: What is a CRUD application?

A1: CRUD stands for Create, Read, Update, and Delete, which are the basic operations used to manage data in a system. In the context of web development, a CRUD application allows users to Create, Read, Update, and Delete records or entries in a database.

Q2: Why use reactive forms in Angular for user input?

A2: Reactive forms in Angular provide a more structured and scalable approach to handling user input. They allow you to manage form state, validation, and user interactions in a declarative way, making it easier to maintain and test your code.

Q3: What is local storage, and why is it used in this application?

A3: Local storage is a web storage API that allows data to be stored locally on a user's browser. In this application, local storage is used to persist the user entries between page refreshes. This ensures that the data remains available even if the user closes or refreshes the browser.

Q4: Can I add form validation to this application?

A4: Yes, you can enhance the application by adding form validation to ensure that user inputs meet specific criteria. Angular provides a robust set of form validation features that you can incorporate into your reactive forms for a better user experience.

Q5: How can I integrate a backend server with this application?

A5: To integrate a backend server, you would typically use Angular's HttpClient module to send HTTP requests to a server that handles data storage and retrieval. You'd need to implement server-side endpoints for CRUD operations and update your Angular application to communicate with these endpoints.

Q6: Is this application secure for handling user data?

A6: While this example focuses on the frontend implementation, security considerations should not be overlooked in a production environment. When dealing with user authentication or sensitive information, it's crucial to implement secure practices such as HTTPS, proper authentication mechanisms, and server-side validation.

Q7: How can I deploy this Angular application?

A7: To deploy your Angular application, you can use platforms like GitHub Pages, Netlify, Vercel, or traditional web hosting. Ensure that you build your Angular project using the ng build command, and then deploy the generated files to a hosting provider of your choice.

Q8: Can I customize the styling of the application?

A8: Absolutely! The provided example uses Bootstrap for styling, but you can customize the styles to match your design preferences. Feel free to modify the CSS classes, colors, and layout to create a visual style that aligns with your project's branding.

Q9: How can I test this application?

A9: Angular provides testing utilities such as TestBed and Jasmine for unit testing. You can write tests for components, services, and other parts of your application to ensure they work as expected. Additionally, Angular CLI comes with a test runner that you can use to execute your tests.

Q10: What are some potential improvements for this CRUD application?

A10: Some potential improvements include adding form validation, implementing user authentication, enhancing the user interface with animations or additional features, and integrating a backend server for more robust data management.

Conclusion

Congratulations! You've successfully created a basic CRUD application in Angular using reactive forms and local storage. This example provides a solid foundation for further customization, such as adding form validations, integrating a backend server, or enhancing the user interface.

Feel free to explore and build upon this foundation to meet your specific requirements. Happy coding!

Comments