Angular 11 Crud Operation

Updated : Apr 14, 2021 in Angular

Angular 11 Crud Operation

In this article, we will learn how to implement a crud operation in Angular 11 with data tables with a bootstrap model popup.

Angular 11 Crud Operation

Angular 11 Environment Setup Prerequisite:

  • Install Visual Studio 2019 Link   or install visual code Link
  • Download NodeJS Link
  • Install Typescript Link
  • Angular CLI 11.2.8. Link

follow the given link for how to setup angular project

After completion of the Angular setup go to the command prompt and create a new project name like my-project-name.

It will take some few minutes for installing ALL REQUIRED PACKAGES AND DEPENDENCIES after completion of installation go to your project path run the given below command lines.

After compilation your project will be run on by default port number is http://localhost:4200/ run this  in your browser.

Angular 11 Crud Operation:

Create component by using following given command line 

ng generate component User

in this example we are using bootstrap model popup for angular 11 crud operation can you follow the given below link for how to install bootstrap model popup in angular. after installation, you have to add the following source code to your files.

modelpopup.service.ts

import { Injectable } from "@angular/core";
import { NgbModal, ModalDismissReasons } from "@ng-bootstrap/ng-bootstrap";
@Injectable({
providedIn: "root",
})
export class ModelpopupService {
closeResult: string;
constructor(private modalService: NgbModal) {}
open(content) {
this.modalService
.open(content, { ariaLabelledBy: "modal-basic-title" })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}

getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return "by pressing ESC";
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return "by clicking on a backdrop";
} else {
return `with: ${reason}`;
}
}
close() {
var x = document.getElementById("closemodel").click();
}
// Open modal with dark section
openModal(customContent) {
this.modalService.open(customContent, { windowClass: "dark-modal" });
}

// Open content with dark section
// openContent() {
// const modalRef = this.modalService.open(NgbdModalContent);
// modalRef.componentInstance.name = 'World';
// }
}

User.component.html

<div class="page-content">
<div class="container-xl container table-responsive">
<div class="row">
<div class="col-sm-6 pageheader">
<i class="fa fa-user" aria-hidden="true"></i>
<h6>Manage Users</h6>
</div>
<div class="col-sm-6 actions">
<a (click)="open(mymodal, $event, 0)" class="btn btn-success"
><i aria-hidden="true" class="fa fa-user"></i>&nbsp;
<span>Add User</span></a
>
</div>
</div>
<table
class="table table-striped row-border hover"
[dtTrigger]="dtTrigger"
datatable
[dtOptions]="dtOption"
>
<thead>
<tr>
<th>#</th>
<th>UserName</th>
<th>MobileNo</th>
<th>Email</th>
<th>Status</th>
<th>CreatedBy</th>
<th>Created Date</th>
<th>Modified Date</th>
<th>Modified By</th>
<th>Version</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let objUsers of listofusers">
<tr>
<td>{{ listofusers.indexOf(objUsers) + 1 }}</td>
<td>{{ objUsers.userName }}</td>
<td>{{ objUsers.userMobileNo }}</td>
<td>{{ objUsers.userEmail }}</td>
<td>
<ui-switch
[checked]="objUsers.status == '1' ? true : false"
(change)="changeststus(objUsers.userId, $event)"
></ui-switch>
</td>
<td>{{ objUsers.createdBy }}</td>
<td>{{ objUsers.createdDate | date: "yyyy-MM-dd" }}</td>
<td>{{ objUsers.lastModifiedDate | date: "yyyy-MM-dd" }}</td>
<td>{{ objUsers.lastModifiedBy }}</td>
<td>{{ objUsers.version }}</td>
<td class="data_action">
<a (click)="open(mymodal, project.id, $event)">
<i class="fa fa-eye" aria-hidden="true"></i>
</a>
<a (click)="open(mymodal, $event, objUsers.userId)" class="edit">
<i class="nb-edit"></i>
</a>
<a
data-toggle="modal"
(click)="deleterecord(sectors.id, $event)"
class="delete"
>
<i class="nb-trash"></i
></a>
</td>
</tr>
</ng-container>
</tbody>
</table>

<div>
<ng-template #mymodal let-modal>
<form (ngSubmit)="onSubmit($event)">
<div class="modal-header">
<div class="pageheader">
<i class="fa fa-user" aria-hidden="true"></i>
<h6 class="modal-title" id="modal-basic-title">{{ title }}</h6>
</div>
<button
type="button"
class="close"
#close
aria-label="Close"
(click)="modal.dismiss('Cross click')"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="context-dada">
<!-- <div class="" *ngIf="EditErrorvalidatrions">
<span class="errorvalidations"> * Edit Fields are required</span>
</div> -->
<!-- <div class="" *ngIf="Errorvalidatrions">
<span class="errorvalidations">*Fields are required</span>
</div> -->
<!-- <div class="" *ngIf="EmailisExist">
<span class="errorvalidations">{{ EmailErorormsg }}</span>
</div> -->

<div class="row">
<div class="col-sm-4">
<strong class="form-label"
>UserName<label class="requiredfield">*</label></strong
>
</div>
<div class="col-sm-8">
<input
[(ngModel)]="FormData.userName"
type="text"
name="userName"
class="form-control"
/>
</div>

<div class="col-sm-4">
<strong class="form-label"
>MobileNo<label class="requiredfield">*</label></strong
>
</div>
<div class="col-sm-8">
<input
[(ngModel)]="FormData.userMobileNo"
type="text"
name="userMobileNo"
class="form-control"
/>
</div>
<div *ngIf="hideEmail" class="row col-sm-12">
<div class="col-sm-4">
<strong class="form-label"
>Email<label class="requiredfield">*</label></strong
>
</div>
<div class="col-sm-8">
<input
[(ngModel)]="FormData.userEmail"
type="text"
name="userEmail"
class="form-control"
/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="save" class="btn btn-primary" />
</div>
</form>
</ng-template>
</div>
</div>
</div>

User.component.ts

import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import { Router } from "@angular/router";
import { DataTableDirective } from "angular-datatables";
import { Subject } from "rxjs";
import { ModelpopupService } from "../../HelperServices/modelpopup.service";
import { SweetAlertService } from "../../HelperServices/sweet-alert.service";
import { UsermanagementModule } from "../../Models/usermanagement/usermanagement.module";
import { UserManagementServiceService } from "../user-management-service.service";
import {
NgbModal,
ModalDismissReasons,
NgbModule,
} from "@ng-bootstrap/ng-bootstrap";
@Component({
selector: "ngx-anikini-user-list",
templateUrl: "./anikini-user-list.component.html",
styleUrls: ["./anikini-user-list.component.scss"],
})
export class UserComponent implements OnInit {
@ViewChild(DataTableDirective, { static: false })
dtElement: DataTableDirective;
dtOption: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();

@ViewChild("close", { static: false }) messageElement: ModalDismissReasons;
hideEmail = false;
AddorEdit = false;
Errorvalidatrions = false;
//EditErrorvalidatrions = false;
listofusers: any;
FormData = {
userId: 0,
userName: "",
userMobileNo: "",
userEmail: "",
};
title: any;
constructor(
private seetalert: SweetAlertService,
private userser: UserManagementServiceService,
private modelpop: ModelpopupService,
public _router: Router
) {}

ngOnInit(): void {
this.Errorvalidatrions = false;
this.dtOption = {
pagingType: "full_numbers",
pageLength: 8,
processing: true,
columnDefs: [
{
targets: [7],
visible: false,
searchable: false,
},
{
targets: [5],
visible: false,
searchable: false,
},
{
targets: [9],
visible: false,
searchable: false,
},
{
targets: [8],
visible: false,
searchable: false,
},
],
dom: "<Blfr<t>ipl>",
buttons: {
dom: {
button: {
tag: "i",
className: "",
},
},
buttons: [
{
titleAttr: "Download as Excel",
extend: "excelHtml5",
className: "custom-btn fa fa-file-excel",
text: "",
},
{
titleAttr: "Print",
extend: "print",
className: "custom-btn fa fa-print",
text: "",
},
{
titleAttr: "Copy as TableData",
extend: "copy",
className: "custom-btn fa fa-files-o",
text: "",
},
{
titleAttr: "Filter",
extend: "colvis",
columns: ":not(:first-child)",
className: "custom-btn fa fa-cog",
text: "",
},
],
},
stateSave: true,
};
this.ListofUsers();
}

ListofUsers() {
this.userser.ListOfUsers().subscribe((resp) => {
this.listofusers = resp.data.sort((a, b) => a - b);
this.dtTrigger.next();
this.rerender();
});
}
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
this.dtTrigger.next();
});
}

ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
}
tempobj: any;
open(mymodal, event, Userid: any) {
event.stopPropagation();
this.FormData.userId = Userid;
if (this.FormData.userId != 0) {
this.title = "Edit User";
this.AddorEdit = false;
this.hideEmail = false;
this.Errorvalidatrions = false;
this.userser.ListOfUsers().subscribe((resp) => {
this.tempobj = resp.data.filter((item) => item.userId === Userid);
this.FormData.userId = Number(this.tempobj[0].userId);
this.FormData.userName = this.tempobj[0].userName;
this.FormData.userMobileNo = this.tempobj[0].userMobileNo;
this.modelpop.open(mymodal);
});
}
if (this.FormData.userId == 0) {
this.title = "Add User";
this.AddorEdit = true;
this.hideEmail = true;
this.Errorvalidatrions = false;
this.clearformdata();
this.modelpop.open(mymodal);
}
}
onSubmit(event) {
console.log(event);
if (this.FormData.userName != "" && this.FormData.userMobileNo != "") {
console.log(this.FormData);
if (
this.AddorEdit == false &&
this.FormData.userId != 0 &&
this.FormData.userEmail == ""
) {
this.userser.Update_Admin_User(this.FormData).subscribe(
(resp) => {
this.userser.ListOfUsers().subscribe((resp) => {
this.listofusers = resp.data.sort((a, b) => b - a);
this.Errorvalidatrions = false;
this.rerender();
this.seetalert.successNotification("Successful");
});
},
(error) => {
console.log(error);
}
);
}
if (
this.AddorEdit == true &&
this.FormData.userId == 0 &&
this.FormData.userEmail != ""
) {
console.log(this.FormData);
this.userser.Create_Admin_User(this.FormData).subscribe(
(resp) => {
this.userser.ListOfUsers().subscribe((resp) => {
this.listofusers = resp.data;
//this.seetalert.successNotification("Successful");
this.rerender();
});
},
(error) => {
console.log(error);
if (error.status == 400) {
this.Errorvalidatrions = false;
// ModalDismissReasons.ESC;
//modal.close('Save click')
this.seetalert.tinyAlert(error.msg);
this.userser.ListOfUsers().subscribe((resp) => {
this.listofusers = resp.data;
this.rerender();
});
}
}
);
} else {
this.Errorvalidatrions = true;
}
} else {
this.Errorvalidatrions = true;
}
}
clearformdata() {
this.FormData.userName = "";
this.FormData.userEmail = "";
this.FormData.userMobileNo = "";
}
status: any;
changeststus(userid: any, event) {
if (event == false) {
this.status = 0;
} else if (event == true) {
this.status = 1;
}
const body = {
lastModifiedBy: 1,
userId: Number(userid),
status: this.status,
};
this.userser.Update_Status(body).subscribe((resp) => {
this.userser.ListOfUsers().subscribe((resp) => {
this.listofusers = resp.data.sort((a, b) => b - a);
this.rerender();
});
});
}
//modal.dismiss('Cross click')
}

User.service.ts

import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { NbCardBodyComponent } from "@nebular/theme";
import { Observable, of, throwError } from "rxjs";
import { retry, catchError, map } from "rxjs/operators";
import { UsermanagementModule } from "../Models/usermanagement/usermanagement.module";

@Injectable({
providedIn: "root",
})
export class UserManagementServiceService {
Base_url = "http://yourbaseurl.com/";
setheaders() {
return (
new HttpHeaders()
//.set('Authorization',null)//,'Bearer ' + this.token
.set("Content-Type", "application/json")
);
}
headerss = this.setheaders();
response: any;
constructor(private httpClient: HttpClient) {}
ListOfUsers() {
const url = this.Base_url + "ecommerce_services/admin/user";
this.response = this.httpClient
.get<any>(url)
.pipe(retry(0), catchError(this.handleError));
return this.response;
}

//{ headers: this.headerss }
Create_Admin_User(body: any) {
delete body.lastModifiedBy;
delete body.userId;
body.createdBy = 1;
const url = this.Base_url + "ecommerce_services/admin/user";
const resp = this.httpClient
.post<any>(url, body)
.pipe(retry(0), catchError(this.handleError));
return resp;
}

//{ headers: this.headerss }
Update_Status(body: any): Observable<any> {
const url =
this.Base_url +
"ecommerce_services/admin/user/updateStatus/" +
body.userId;
const response = this.httpClient
.post<any>(url, body)
.pipe(retry(0), catchError(this.handleError));
return response;
}

Update_Admin_User(body: any) {
delete body.userEmail;
delete body.createdBy;
body.lastModifiedBy = 1;
const url = this.Base_url + "ecommerce_services/admin/user";
console.log(url);
const response = this.httpClient
.put<any>(url, body)
.pipe(retry(0), catchError(this.handleError));
return response;
}

// Handle API errors
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error("An error occurred:", error.error.message);
console.log(error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(error.error.status);
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.error}`
);
}
// return an observable with a user-facing error message
return throwError({ status: error.error.status, msg: error.error.msg });
}
}

Output:

Angular 11 Crud Operation
Angular 11 Crud Operation
Angular 11 Crud Operation

Note: some of the component names, selector names, and file path you will have to change according to your component name in the above source code

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x