A Complete Guide of CRUD Operations in Angular (Using Modal, Simple Forms) | Beginners

Iqra Jamil
8 min readOct 25, 2022

--

Building a CRUD application is a basic step to learning to integrate the front-end with a back-end database. CRUD stands for the four functions create, read, update, and delete in computer programming. They are used to implement persistent storage applications and relational database applications:

  • Create: A create operation allows you to add a new record to a table.
  • Read: A read operation allows you to read record details based on the primary key.
  • Update: An update operation allows you to modify an existing record based on the primary key.
  • Delete: A delete operation allows you to delete any specific record based on the primary key.

So, in this article, you’ll learn how to perform CRUD operations in Angular.

Let’s dive in.

Prerequisites:

Install Node.js, Visual Studio and Angular CLI.

To check if Node.js is already installed on your machine, check for its version using the following command. If it is already installed, it will return the version number, as shown in the following screenshot. Otherwise, it will return an error.

node -v
Node version

Similarly, check whether the npm and Angular CLI are already installed with the following command to check the version.

npm -v
ng version
Npm and Angular Version

If they aren’t installed, install them with the details available in the following table.

╔═══════════╦═══════════════════════════════════╗
║ Node.js ║ https://nodejs.org/en/download/
╠═══════════╬═══════════════════════════════════╣
║ Npm ║ If you install node.js, it will ║
║ ║ install npm, too. ║
╠═══════════╬═══════════════════════════════════╣
║ Angular ║ Run the following command: ║
║ CLI ║ npm i @angular/cli
╚═══════════╩═══════════════════════════════════╝

Create and Run Angular Project:

Create a “Learn-CRUD-Operations” folder and open that folder in vs code.

Open terminal.

Create an Angular Project using the following command.

ng new crud-operations

Select “Y” for Angular routing and SCSS file for stylesheet format.

Now, go to your angular project and run your project. Following are the commands for it.

cd crud-operations
ng serve

By default, your browser will look like this.

Basic Setup:

Now, Let’s make the changes that we need for our project. First, Erase all code in “app.component.html” except the last line i.e,

<router-outlet></router-outlet>

Note: On the browser, you’ll see a blank page now. Don’t forget to save every change you made. :D

Create a new component with the “crud” name.

ng g c crud

Add a newly created component path in the “app-routing-module.ts ” routes array.

const routes: Routes = [{ path: 'crud', component: CrudComponent }];

Remember to give a “crud” path in the browser from now on to see your changes. :)

localhost:port/crud

Create a data folder in the “src” folder. Add a “users.json” file in the “data” folder. Paste the following data in that file.

[{"id": 1,"name": "Joey","email": "joey@gmail.com","gender": "male"},{"id": 2,"name": "Chandler","email": "chandler@gmail.com","gender": "male"},{"id": 3,"name": "Ross","email": "ross@gmail.com","gender": "male"},{"id": 4,"name": "Monica","email": "monica@gmail.com","gender": "female"}]

See the below image for a better understanding.

For importing the JSON file in your angular component, import these two code blocks in “angularCompilerOptions” in your “tsconfig.json” file

"resolveJsonModule": true,"esModuleInterop": true,

We will be using bootstrap too. Install it by using the following command.

ng add @ng-bootstrap/ng-bootstrap

Add the below line to your styles array in the “angular.json” file for importing bootstrap.

"node_modules/bootstrap/dist/css/bootstrap.min.css"

The following CSS styles are used in this project. Copy and paste them into your “styles.scss” file. You can add global styles to this file, and also import other style files.

.bread-crumb {padding-bottom: 30px;display: flex;margin-top: 20px;}h3{margin-left: 25px;margin-top: 10px;}.add-btn {margin-left: auto;margin-right: 30px;}.table-div{margin-left: 20px;margin-right: 20px;box-shadow: 1px 1px 1px #999;}table{text-align-last: center;table-layout: fixed;}thead{background: black;color: white;}.btn-red{--bs-btn-bg:rgb(250, 37, 37) !important;--bs-btn-hover-bg: red;margin-left: 6px;}

Create an images folder and add all SVG files to the assets folder. (Access the images folder used in this project)

Implementing CRUD Operations:

Now that we have added all dependencies in the project, the next step is to write crud operations.

Displaying JSON Data:

Import data in the “crud.component.ts” file.

import data from '../../data/users.json';

Make a User interface in the “crud.component.ts” file.

interface Users {id: number;name: string;email: string;gender: string;}

Declare user array of User type.

users: Users[] = [];

In ngOnInit() function, initialize users. Stop there if you don’t know about Lifecycle hooks, Learn now. :)

this.users = data

Up till now, your “crud.component.ts” file will look like this.

Now, Let's make a table in the “crud.component.html” file to display data.

<div class="container-fluid"><div class="row"><div class="col-lg-12"><div class="bread-crumb"><h3 title="Students List">Students List</h3>
</div>
<div class="table-div"><table class="table table-hover table-striped table-bordered"><thead><tr><th title="ID">ID</th><th title="Name">Name</th><th title="Email">Email</th><th title="Gender">Gender</th></tr></thead><tbody><tr *ngFor="let i of users"><td>{{ i.id }}</td><td>{{ i.name }}</td><td>{{ i.email }}</td><td>{{ i.gender }}</td></tr></tbody></table></div>
</div>
</div></div>

Your browser will look like this.

Delete Operation:

For deleting, create a column with an actions header and a delete button in the “crud.component.html” file. Add bolded code in your HTML file.

<table class="table table-hover table-striped table-bordered"><thead><tr><th title="ID">ID</th><th title="Name">Name</th><th title="Email">Email</th><th title="Gender">Gender</th><th [width]="128" title="Actions">Actions</th></tr></thead><tbody><tr *ngFor="let i of users"><td>{{ i.id }}</td><td>{{ i.name }}</td><td>{{ i.email }}</td><td>{{ i.gender }}</td><td><button class="btn btn-red" (click)="deleteUser(i.id)" title="Delete"><img src="../../assets/images/trash.svg" width="15" /></button></td></tr></tbody></table>

Now create a delete function in the “crud.component.ts” file.

deleteUser(selectedUserId: any) {const index = this.users.findIndex(x => x.id == selectedUserId)this.users.splice(index, 1)}

Your browser will look like this (I have deleted the first record for verifying the delete function). :)

Add/Edit:

For adding and editing, We will be using modal and forms. Simple forms are used here. Let's import all dependencies needed for this part.

Add Form Modules in the “app.module.ts” file.

imports: [BrowserModule,AppRoutingModule,NgbModule,FormsModule],

Import the following libraries in the “crud.component.ts” file.

import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { NgForm } from '@angular/forms';

Initialize modal service.

constructor(private modalService: NgbModal) { }

Create the “Add” and “Edit” buttons in the “crud.component.html” file. (Add bolded code in your HTML file)

<div class="container-fluid"><div class="row"><div class="col-lg-12"><div class="bread-crumb"><h3 title="Students List">Students List</h3><button class="btn btn-primary add-btn" (click)="open(content)" title="Add New Student"><img src="../../assets/images/plus.svg" />Add New Student</button></div><div class="table-div"><table class="table table-hover table-striped table-bordered"><thead><tr><th title="ID">ID</th><th title="Name">Name</th><th title="Email">Email</th><th title="Gender">Gender</th><th [width]="128" title="Actions">Actions</th></tr></thead><tbody><tr *ngFor="let i of users"><td>{{ i.id }}</td><td>{{ i.name }}</td><td>{{ i.email }}</td><td>{{ i.gender }}</td><td><button class="btn btn-primary" (click)="editUser(i, content)" title="Edit"><img src="../../assets/images/pencil.svg" width="15" /></button><button class="btn btn-red" (click)="deleteUser(i.id)" title="Delete"><img src="../../assets/images/trash.svg" width="15" /></button></td></tr></tbody></table></div></div></div></div>

Now add the following bolded code. It contains a simple form on the modal opening.

<div class="container-fluid"><div class="row"><div class="col-lg-12"><div class="bread-crumb"><h3 title="Students List">Students List</h3><button class="btn btn-primary add-btn" (click)="open(content)" title="Add New Student"><img src="../../assets/images/plus.svg" />Add New Student</button></div><div class="table-div"><table class="table table-hover table-striped table-bordered"><thead><tr><th title="ID">ID</th><th title="Name">Name</th><th title="Email">Email</th><th title="Gender">Gender</th><th [width]="128" title="Actions">Actions</th></tr></thead><tbody><tr *ngFor="let i of users"><td>{{ i.id }}</td><td>{{ i.name }}</td><td>{{ i.email }}</td><td>{{ i.gender }}</td><td><button class="btn btn-primary" (click)="editUser(i, content)" title="Edit"><img src="../../assets/images/pencil.svg" width="15" /></button><button class="btn btn-red" (click)="deleteUser(i.id)" title="Delete"><img src="../../assets/images/trash.svg" width="15" /></button></td></tr></tbody></table></div><ng-template #content let-modal><div class="modal-header"><h4 class="modal-title" id="modal-basic-title">{{selectedUser? "Edit Student": "New Student"}}</h4><button type="button" class="close" aria-label="Close" (click)="close(modal)"><span aria-hidden="true">&times;</span></button></div><div class="modal-body"><!-- Simple Form --><form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate><div class="form-group"><label for="name">Name</label><div class="input-group"><input id="name" name="name" class="form-control" [(ngModel)]="name"></div></div><div class="form-group"><label for="email">Email</label><div class="input-group"><input id="email" name="email" class="form-control" [(ngModel)]="email"></div></div><p><input type="radio" value="male" name="gender" [(ngModel)]="gender"> Male<input type="radio" value="female" name="gender" [(ngModel)]="gender"> Female</p><div><div class="text-center"><button data-dismiss="modal" class="btn btn-info">Submit</button></div></div></form></div></ng-template></div></div></div>

Add the following code to your “crud.component.ts” file.

email: any;gender: any;name: anyselectedUser: any;open(content: any) {this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result}close(closeModal: any) {this.setAllValues();closeModal.dismiss('Cross click');}setAllValues() {this.email = ""this.name = ""this.gender = ""this.selectedUser = null}addStudent(values: any) {const size = this.users?.length - 1values.id = this.users[size]?.id + 1this.users.push(values);this.setAllValues();}editUser(selectedUser: any, content: any) {this.selectedUser = selectedUserthis.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' })this.email = selectedUser?.emailthis.name = selectedUser?.namethis.gender = selectedUser?.gender}updateStudentInTable(values: any) {this.users.forEach(x => {if (x.id == this.selectedUser.id) {x.name = values.namex.email = values.emailx.gender = values.gender}});this.setAllValues();}onSubmit(f: NgForm) {const formValues = f?.value;if (this.selectedUser) {this.updateStudentInTable(formValues)}else {this.addStudent(formValues)}this.modalService.dismissAll(); //dismiss the modal}

This is how your modal and browser screen will look like.

Summary

In this tutorial, we learnt about crud operations and implemented them in the simplest way in Angular. Access the whole project code on Github here.

Hurray! You made it until the end. Be proud of yourself. :D

Would love to hear from you. :)

For upcoming stories, you should follow my profile Iqra Jamil.

That’s it, guys! Have fun, keep learning & always coding!

--

--