Home »
Angular JS
Angular CRUD Application Using JSON
By IncludeHelp Last updated : September 1, 2024
Here, we will develop a User Management System (UMS) using an Angular CRUD application, with JSON as the database. First, let's discuss what a CRUD application is and how it can be used to develop applications such as UMS, Employee Management Systems (EMS), etc.
What is CRUD Application?
A CRUD application is a type of software that performs the basic functions of data management. The CRUD stands for:
- Create: Add new data or records into the database.
- Read: Retrieve and display existing data or records from the database.
- Update: Modify or edit existing data or records.
- Delete: Remove data or records from the database.
CRUD Functionalities
Using CRUD functionality, we will develop a UMS application that supports the following features:
- Admin can create a user.
- Admin can view a user's details.
- Admin can update existing user details.
- Admin can delete a user.
Synopsys of Angular CRUD Application with JSON
Below are the images that illustrate how the application will look.
1. Dashboard
The dashboard will look like:
2. User Details
User details will display like this:
3. Create User
New user creation form will look like this:
4. Update User
Here we will update the user's details. It will look like:
5. Delete User
Deleting a user's details will be like this:
After viewing the images above, you will have a better understanding of the UMS application, its pages, and its functionalities.
Steps to Create Angular CRUD Application Using JSON
The steps to create the Angular UMS application using CRUD operations and HTTP services as follows:
- Step 1: Create a folder on your system.
- Step 2: Open that folder in an IDE such as Visual Studio Code.
- Step 3: Open the terminal in your editor.
- Step 4: Install Angular CLI using the following command:
npm install @angular/cli -g
- Step 5: Create a new Angular application using the following command:
ng new myApp --routing --skip-server
- Step 6: Navigate to the newly created application folder using the following command:
cd myApp
- Step 7: Create a dashboard component using the following command:
ng generate component UserDashboard
Or
ng g c UserDashboard
- Step 8: Open the app.component.html file, remove all existing code, and leave only:
<router-outlet></router-outlet>
- Step 9: Run the application using the following command:
npm start
Or
ng serve
- Step 10: Navigate to the assets folder using the following commands:
cd src/assets
- Step 11: Create a .json file in the assets folder, e.g., db.json
- Step 12: Install json-server in your Angular application using the following command:
npm install json-server
- Step 13: Run json-server using the following command:
npx json-server --watch db.json
- Step 14: Access the JSON data at the following URL:
http://localhost:3000
- Step 15: Add dummy data to your db.json file as follows:
{
"users": [{
"id": 1,
"name": "Mahesh",
"email": "[email protected]",
"mobile": "9023456718",
"address": "Hyderabad, India"
}]
}
- Step 16: Create a services folder within the app folder for performing CRUD operations using HTTP requests.
- Step 17: Go to the services folder and create an Angular service using the following command:
ng generate service auth
Or
ng g s auth
- Step 18: Import HttpClientModule in your app.module.ts file.
- Step 19: Import HttpClient in auth.service.ts using the following command:
import { HttpClient } from '@angular/common/http';
- Step 20: Write all the provided code in your respective file correctly from the given file:
- Step 21: Now start your application and JSON using the following commands:
For application:
npm start or ng serve
For JSON:
npx json-server -watch db.json
Code for Angular CRUD Application Using JSON
Below is the complete code for Angular CRUD application Using JSON:
1. App Module (app.module.ts file)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserDashboardComponent } from './user-dashboard/user-dashboard.component';
import { HttpClientModule } from '@angular/common/http';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ViewUserComponent } from './view-user/view-user.component';
import { UpdateUserComponent } from './update-user/update-user.component';
import { CreateUserComponent } from './create-user/create-user.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
UserDashboardComponent,
PageNotFoundComponent,
ViewUserComponent,
UpdateUserComponent,
CreateUserComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ReactiveFormsModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2. User Dashboard Component
File: user-dashboard-component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-user-dashboard',
templateUrl: './user-dashboard.component.html',
styleUrl: './user-dashboard.component.css'
})
export class UserDashboardComponent implements OnInit{
constructor(private auth: AuthService, private router: Router){}
allUsers: any;
count = 0;
ngOnInit(): void {
this.auth.getAllUsers().subscribe(res=>{
this.allUsers = res;
console.log(this.allUsers);
this.count = this.allUsers.length;
});
}
delete(id: any){
if(confirm("Are you sure?") == true){
this.auth.deleteUserBydId(id).subscribe(res=>{
location.reload();
});
}
else{
this.router.navigate(['dashboard']);
}
}
}
File: user-dashboard-component.html
<div class="main">
<div class="heading">
<h1>User Management System (UMS)</h1>
</div>
<div class="container">
<div class="data">
<div class="count">
<p>Total Users: {{count}}</p>
</div>
<div class="addUser">
<a routerLink="/dashboard/user/create">Add New User</a>
</div>
</div>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Address</th>
<th>Actions</th>
</tr>
<tr *ngFor = "let u of allUsers; let i = index;">
<td>{{u.name}}</td>
<td>{{u.email}}</td>
<td>{{u.mobile}}</td>
<td>{{u.address}}</td>
<td>
<a [routerLink]="['/dashboard/user/view', u.id]">View</a>|
<a [routerLink]="['/dashboard/user/update', u.id]">Update</a>|
<a href="" (click) = "delete(u.id)">Delete</a>
</td>
</tr>
</table>
</div>
</div>
File: user-dashboard-component.css
*{
box-sizing: border-box;
}
.main{
width: 90%;
background-color: rgb(211, 206, 206);
margin: auto;
padding: 10px;
}
.heading h1{
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 10px 0px;
font-weight: bold;
}
.data{
width: 100%;
margin: 10px auto;
display: flex;
justify-content: space-between;
}
.count{
font-size: 20px;
font-weight: 600;
}
.addUser a{
text-decoration: none;
width: 100px;
padding: 10px;
background-color: antiquewhite;
border-radius: 5px;
font-size: 18px;
}
.container{
width: 100%;
margin: 50px auto;
overflow-x: auto;
font-size: 18px;
}
.container table{
width: 100%;
border-collapse: collapse;
}
.container th, td{
border: 1px solid black;
text-align: center;
}
.container table th{
padding: 10px;
}
.container table th, td{
border: 1px solid black;
border-collapse: collapse;
}
.container table td{
padding: 7px;
}
.container table tr td a{
text-decoration: none;
padding: 10px;
}
@media (max-width: 768px) {
.container table {
font-size: 14px;
}
}
3. Create User Component
File: create-user-component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-create-user',
templateUrl: './create-user.component.html',
styleUrl: './create-user.component.css'
})
export class CreateUserComponent implements OnInit{
constructor(private router: Router, private fb: FormBuilder, private auth: AuthService){}
createForm: FormGroup = new FormGroup({});
ngOnInit(): void {
this.createForm = this.fb.group({
'name': new FormControl(''),
'email': new FormControl(''),
'gender': new FormControl(''),
'mobile': new FormControl(''),
'address': new FormControl(''),
'createddate': new FormControl('')
});
}
back(){
this.router.navigate(['dashboard']);
}
msg: string = '';
isRight = '';
createUser(){
let name = this.createForm.get('name')?.value;
let email = this.createForm.get('email')?.value;
let mobile = this.createForm.get('mobile')?.value;
let address = this.createForm.get('address')?.value;
if(name.trim().length == 0){
this.msg = 'Name is required...!';
this.isRight = 'invalid';
}
else if(email.trim().length == 0){
this.msg = 'Email is required...!'
this.isRight = 'invalid';
}
else if (mobile.trim().length === 0 || mobile.trim().length !== 10) {
this.msg = "Invalid mobile number";
this.isRight = 'invalid';
}
else if(address.trim().length == 0 || address.length < 10){
this.msg = "Address is required atleast 10 characters";
this.isRight = 'invalid';
}
else{
this.auth.createUser(this.createForm.value).subscribe(res=>{
this.msg = "User created successfully redirecting to dashboard...";
this.isRight = 'valid';
setTimeout(()=>{
this.router.navigate(['dashboard']);
}, 3000);
});
}
}
}
File: create-user.component.html
<div class="main">
<div class="heading">
<h1>User Management System (UMS)</h1>
</div>
<div class="container">
<h1>Create User Form</h1>
<form [formGroup]="createForm">
<input type="text" placeholder="Name" formControlName="name">
<input type="text" placeholder="Email" formControlName="email">
<input type="radio" id="male" value="male" name="gender" formControlName="gender"><label for="">Male</label>
<input type="radio" id="female" value="female" name="gender" formControlName="gender"><label for="">Female</label>
<input type="text" placeholder="Mobile" formControlName="mobile">
<input type="text" placeholder="Address" formControlName="address">
<input type="date" placeholder="Created date" formControlName="createddate">
<button (click)="createUser()">Create</button>
<button (click)="back()">Back</button>
<span [class]="isRight">{{msg}}</span>
</form>
</div>
</div>
File: create-user.component.css
*{
box-sizing: border-box;
}
.main{
width: 90%;
background-color: rgb(211, 206, 206);
margin: auto;
padding: 10px;
}
.heading h1{
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 10px 0px;
font-weight: bold;
}
.container{
width: 100%;
margin: 50px auto;
}
form{
width: 100%;
padding: 10px 0px;
margin: 20px auto;
}
form input[type='text'], input[type='date']{
display: block;
width: 80%;
padding: 12px 10px;
margin: 20px 2px;
font-size: 18px;
}
form input[type='radio']{
padding: 10px 12px;
margin: 0px 0px;
width: 20px;
height: 20px;
}
form label{
font-size: 18px;
margin: 0px 10px;
}
form button{
width: 100px;
padding: 10px;
font-size: 18px;
border: none;
border-radius: 5px;
margin: 0px 5px;
}
form button:nth-child(1){
background-color: antiquewhite;
transition: 0.5s;
}
.invalid{
color: red;
font-size: 17px;
}
.valid{
color: green;
font-size: 17px;
}
4. Update User Component
File: update-user.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Component({
selector: 'app-update-user',
templateUrl: './update-user.component.html',
styleUrl: './update-user.component.css'
})
export class UpdateUserComponent implements OnInit{
constructor(private fb: FormBuilder, private router: Router, private route: ActivatedRoute, private auth: AuthService){}
uid: any;
userDetails: any;
updateForm: FormGroup = new FormGroup({});
dataloaded: boolean = true;
ngOnInit(): void {
this.dataloaded = false;
this.route.params.subscribe(res=>{
this.uid = res['id'];
//console.log(this.id);
});
if(this.uid !== ''){
this.auth.getUserById(this.uid)
.toPromise()
.then(res=>{
this.userDetails = res;
console.log(this.userDetails);
this.updateForm = this.fb.group({
'name': new FormControl(this.userDetails.name),
'email': new FormControl(this.userDetails.email),
'gender': new FormControl(this.userDetails.gender),
'mobile': new FormControl(this.userDetails.mobile),
'address': new FormControl(this.userDetails.address),
'createddate': new FormControl(this.userDetails.createddate)
})
this.dataloaded = true;
}).catch(err=>{
console.log(err);
this.dataloaded = true;
});
}
}
msg = '';
isRight = '';
updateUser(){
let name = this.updateForm.get('name')?.value;
let email = this.updateForm.get('email')?.value;
let mobile = this.updateForm.get('mobile')?.value;
let address = this.updateForm.get('address')?.value;
let createdDate = this.updateForm.get('createddate')?.value;
if(name.trim().length == 0){
this.msg = 'Name is required...!';
this.isRight = 'invalid';
}
else if(email.trim().length == 0){
this.msg = 'Email is required...!'
this.isRight = 'invalid';
}
else if (mobile.trim().length === 0 || mobile.trim().length !== 10) {
this.msg = "Invalid mobile number";
this.isRight = 'invalid';
}
else if(address.trim().length == 0 || address.length < 10){
this.msg = "Address is required atleast 10 characters";
this.isRight = 'invalid';
}
else{
this.auth.updateUser(this.uid, this.updateForm.value).subscribe(res=>{
this.msg = "User details updated successfully redirecting to view user...";
this.isRight = 'valid';
setTimeout(()=>{
this.router.navigate(['dashboard/user/view/' + this.uid]);
}, 3000);
});
}
}
back(){
this.router.navigate(['dashboard']);
}
}
File: update-user.component.html
<div class="main" *ngIf="dataloaded">
<div class="heading">
<h1>User Management System (UMS)</h1>
</div>
<div class="container">
<h1>Update User Details</h1>
<form [formGroup]="updateForm">
<input type="text" placeholder="Name" formControlName="name">
<input type="text" placeholder="Email" formControlName="email">
<div>
<input type="radio" id="male" value="male" formControlName="gender">
<label for="male">Male</label>
</div>
<div>
<input type="radio" id="female" value="female" formControlName="gender">
<label for="female">Female</label>
</div>
<input type="text" placeholder="Mobile" formControlName="mobile">
<input type="text" placeholder="Address" formControlName="address">
<input type="date" formControlName="createddate">
<button type="button" (click)="updateUser()">Update</button>
<button type="button" (click)="back()">Back</button>
<span [ngClass]="isRight">{{msg}}</span>
</form>
</div>
</div>
File: update-user.component.css
*{
box-sizing: border-box;
}
.main{
width: 90%;
background-color: rgb(211, 206, 206);
margin: auto;
padding: 10px;
}
.heading h1{
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 10px 0px;
font-weight: bold;
}
.container{
width: 100%;
margin: 50px auto;
}
form{
width: 100%;
padding: 10px 0px;
margin: 20px auto;
}
form input[type='text'], input[type='date']{
display: block;
width: 80%;
padding: 12px 10px;
margin: 20px 2px;
font-size: 18px;
}
form input[type='radio']{
padding: 10px 12px;
margin: 0px 0px;
width: 20px;
height: 20px;
}
form label{
font-size: 18px;
margin: 0px 10px;
}
form button{
width: 100px;
padding: 10px;
font-size: 18px;
border: none;
border-radius: 5px;
margin: 0px 5px;
}
form button:nth-child(1){
background-color: antiquewhite;
transition: 0.5s;
}
.invalid{
color: red;
font-size: 17px;
}
.valid{
color: green;
font-size: 17px;
}
5. View User Component
File: view-user.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-view-user',
templateUrl: './view-user.component.html',
styleUrl: './view-user.component.css'
})
export class ViewUserComponent implements OnInit{
constructor(private auth: AuthService, private route: ActivatedRoute){}
id : any;
userDetails: any;
isLoaded:boolean = false;
ngOnInit(): void {
this.route.params.subscribe(res=>{
this.id = res['id'];
//console.log(this.id);
this.auth.getUserById(this.id).subscribe(res=>{
this.userDetails = res;
//console.log(this.userDetails);
this.isLoaded = true;
});
});
}
}
File: view-user.component.html
<div class="main" *ngIf="isLoaded">
<div class="heading">
<h1>User Management System (UMS)</h1>
</div>
<div class="container">
<h2>User Details</h2>
<ul>
<li>Id: {{userDetails.id}}</li>
<li>Name: {{userDetails.name}}</li>
<li>Email: {{userDetails.email}}</li>
<li>Gender: {{userDetails.gender}}</li>
<li>Mobile: {{userDetails.mobile}}</li>
<li>Address: {{userDetails.address}}</li>
<li>Created date: {{userDetails.createddate}}</li>
</ul><br>
<a routerLink = "/dashboard">Back</a>
</div>
</div>
File: view-user.component.css
*{
box-sizing: border-box;
}
.main{
width: 90%;
background-color: rgb(211, 206, 206);
margin: auto;
padding: 10px;
}
.heading h1{
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: 10px 0px;
font-weight: bold;
}
.container{
width: 100%;
margin: 50px auto;
}
.container h2{
margin: 10px 30px;
}
.container ul{
list-style: none;
width: 100%;
}
.container ul li{
padding: 12px;
font-size: 20px;
}
.container ul li:nth-child(even){
background-color: rgb(198, 194, 190);
}
.container ul li:nth-child(odd){
background-color: rgb(167, 172, 172);
}
.main a{
width: 100px;
margin: 20px 30px;
padding: 15px 50px;
cursor: pointer;
font-size: 20px;
background-color: beige;
border-radius: 5px;
text-decoration: none;
color: black;
}
6. Service (auth.service.ts)
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root' // root level access to over all the components
})
export class AuthService {
baseURL : string = "http://localhost:3000/users";
constructor(private http: HttpClient) { }
getAllUsers(){
return this.http.get(this.baseURL);
}
getUserById(id: any){
return this.http.get(this.baseURL + "/" + id);
}
deleteUserBydId(id: any){
return this.http.delete(this.baseURL + '/' + id);
}
createUser(obj: any){
return this.http.post(this.baseURL + "/", obj);
}
updateUser(id: any, obj: any) {
return this.http.put(`${this.baseURL}/${id}`, obj);
}
}
7. JSON data (db.json)
{
"users": [
{
"name": "Rahul Verma",
"email": "[email protected]",
"gender": "male",
"mobile": "8429608353",
"address": "Lucknow Sultanpur 228151, U.P India",
"createddate": "2024-08-29",
"id": "327c"
},
{
"name": "Reena Gupta",
"email": "[email protected]",
"gender": "female",
"mobile": "9304719823",
"address": "Ranchi Jharkhand",
"createddate": "2024-08-29",
"id": "4c13"
},
{
"name": "Md Arif",
"email": "[email protected]",
"gender": "male",
"mobile": "1234567898",
"address": "Kanpur U.P India",
"createddate": "2024-08-29",
"id": "a34d"
},
{
"name": "Shikha Verma",
"email": "[email protected]",
"gender": "female",
"mobile": "6303289441",
"address": "Hyderabad Telangana",
"createddate": "2024-08-29",
"id": "1dbf"
}
]
}