,

Angular 13 CRUD Operations using Angular Material UI, json-server, and Angular Reactive Forms

Posted by


Angular 13 CRUD with Angular Material UI | json-server | Angular Reactive Form

If you are an Angular developer, you must be familiar with the concept of CRUD operations. CRUD stands for Create, Read, Update, and Delete, and it is an essential part of building any application. In this article, we will explore how to implement CRUD operations using Angular 13, Angular Material UI, json-server, and Angular Reactive Forms.

What is Angular Material UI?

Angular Material is a UI component library for Angular that provides a set of reusable and high-quality UI components. It follows the Material Design principles developed by Google, which ensures a consistent and visually appealing user interface. Angular Material UI makes it easier to build responsive and mobile-friendly applications.

What is json-server?

json-server is a simple and lightweight database server that is used to create a fake REST API. It allows you to quickly prototype and develop your front-end applications without the need for a back-end server. With json-server, you can easily perform CRUD operations on your data using standard HTTP methods.

Setting up the project

To get started, make sure you have the latest version of Angular CLI installed on your machine. Open your command prompt or terminal and run the following command:

npm install -g @angular/cli

Once the installation is complete, you can create a new Angular project by running the following command:

ng new angular-crud

Next, navigate to the project directory:

cd angular-crud

Install Angular Material UI by running the following command:

ng add @angular/material

This command will prompt you to choose a pre-built theme and other configuration options. Select the desired options and let the installation complete.

Install json-server by running the following command:

npm install -g json-server

Creating the Angular Reactive Form

To implement CRUD operations, we need to create a form for adding and editing data. Angular Reactive Forms provide a powerful way to build complex and dynamic forms with validation.

In your project directory, open the app.module.ts file and import the ReactiveFormsModule from @angular/forms:

import { ReactiveFormsModule } from '@angular/forms';

Next, add the ReactiveFormsModule to the imports array:

imports: [
...
ReactiveFormsModule
]

Save the changes and open the app.component.ts file.

Define the form controls and form group in your AppComponent class:

export class AppComponent {
userForm: FormGroup;

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
this.userForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
phone: ['', Validators.required]
});
}

get f() { return this.userForm.controls; }
}

In the above code, we have defined three form controls: name, email, and phone. The Validators.required and Validators.email are used for form validation.

Next, let’s create the form in our app.component.html file:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<h2>Add User</h2>

<div class="form-group">
<label for="name">Name</label>
<input type="text" formControlName="name" class="form-control">
<div *ngIf="f.name.touched && f.name.errors" class="text-danger">
<div *ngIf="f.name.errors.required">Name is required</div>
</div>
</div>

<div class="form-group">
<label for="email">Email</label>
<input type="text" formControlName="email" class="form-control">
<div *ngIf="f.email.touched && f.email.errors" class="text-danger">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Invalid email address</div>
</div>
</div>

<div class="form-group">
<label for="phone">Phone</label>
<input type="text" formControlName="phone" class="form-control">
<div *ngIf="f.phone.touched && f.phone.errors" class="text-danger">
<div *ngIf="f.phone.errors.required">Phone is required</div>
</div>
</div>

<button type="submit" [disabled]="userForm.invalid" class="btn btn-primary">Submit</button>
</form>

In the above code, we have used formControlName directive to bind the form controls to their respective HTML elements. We have also added validation messages using *ngIf directive to show error messages when the form controls are touched and have validation errors.

Next, let’s create the onSubmit method in our app.component.ts file:

onSubmit() {
if (this.userForm.invalid) {
return;
}

// Implement the logic to add or edit the user data here
}

In the above code, we are checking if the form is invalid, and if it is, we return to prevent further execution. You can implement the logic to add or edit the user data inside the onSubmit method.

Performing CRUD operations

Now that we have created the form, let’s implement the CRUD operations using json-server.

Create a file named db.json in your project directory and add the following data:

{
"users": []
}

This file will serve as our database for storing user data.

In your project directory, create a file named server.js and add the following code:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

const port = process.env.PORT || 3000;

server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use('/api', router);

server.listen(port, () => {
console.log(`JSON Server is running on port ${port}`);
});

In the above code, we are creating a simple server using json-server and configuring it to use our db.json file as the data source. We are also defining a base URL (/api) for our API endpoints.

To start the json-server, open your command prompt or terminal and navigate to your project directory. Run the following command:

node server.js

Now, you should see a message saying “JSON Server is running on port 3000” or the port you have specified.

In your app.component.ts file, add the following code to make HTTP requests to the json-server API:

import { HttpClient } from '@angular/common/http';

constructor(private httpClient: HttpClient) { }

onSubmit() {
if (this.userForm.invalid) {
return;
}

const user = {
name: this.userForm.value.name,
email: this.userForm.value.email,
phone: this.userForm.value.phone
};

this.httpClient.post('http://localhost:3000/api/users', user)
.subscribe((response) => {
console.log('User added successfully');
this.userForm.reset();
});
}

In the above code, we are making a POST request to the /api/users endpoint of our json-server API to add a new user. We are using the Angular HttpClient module to make the HTTP request.

Similarly, you can implement the logic for reading, updating, and deleting the user data by making the respective HTTP requests to the json-server API.

Conclusion

In this article, we have learned how to implement CRUD operations in Angular 13 using Angular Material UI, json-server, and Angular Reactive Forms. We have created a form using Angular Reactive Forms for adding and editing user data. We have also used json-server to create a fake REST API for performing CRUD operations on the user data. By following these steps, you can easily create a data-driven application with Angular 13.

0 0 votes
Article Rating
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mansi Sawant
8 months ago

Hello Sir
One of the most important video is here for Angular (plz check everyone).
All good info with great explanation.
I'm continuously watching for two times in one day can't replace this video on overall yt channels .
Thank you sir
You are a great ❣️

Kishore kumar L
8 months ago

Provide button disable logic until the form is changed in edit

Mohamed Elyamani
8 months ago

where is the source code link in desc is faild

Shreyaa Karanjkar
8 months ago

BEST CRUD Project , without any errors or getting stuck, the way you explain is awesome… THANKS SO MUCHHHHHHH

Samiksha Naikade
8 months ago

Hello thanks for this amazing video…
Actually i did everything very correctly but my update button is not showing any action.
And also the next day i run the code it's only giving me the alert message "Error while updating the product" and no actions are performing

Mumtaz Ali
8 months ago

Thank you for this great video

TJ Akshay
8 months ago

👍

vedika singh
8 months ago

sir can you share CRUD Operations Using Modal Popup

Aryan bhavsar
8 months ago

npm install json-server in my case this command is working in angular 16

Preksha
8 months ago

Thank you so so so much you helped me alot

Kaustubh Nandankar
8 months ago

Thank you for such amazing content. God bless you always. 😀

Anju K
8 months ago

Hi … The video is superb.. but I have one issue. My backend is nodejs. Data is obtained as array of objects. While clicking edit button data is not obtained from the table row

Adil Qureshi
8 months ago

jason server not found how to fix the problem sir

tebogo mabusela
8 months ago

I love and love this video. very easy to follow. See you on the next one.

Shubham Bahre
8 months ago

Please create timestamps/chapters in the video. It is helpful to navigate.

Dao Quang Linh (FPL HN)
8 months ago

how can i upload file image

Jasmine Fernandez
8 months ago

Is this firebase?

Nguyen Duc Truong
8 months ago

hello sir can you tell me how to upload pictures?

zang zang
8 months ago

thank you very nice !

Pramod Gautam
8 months ago

I am facing problem in this project