CRUD Operations With .Net 5.0 In Angular 13

In this article, we are going to learn how to perform CRUD operations in Angular 13.

For .Net 5.0 API please click here


  • Basic knowledge of Angular
  • Code editor like Visual Studio Code

Create, Read, Update, and Delete operations in Angular 13

First, create a new project in Angular

ng new BookCRUD

Then open the project in visual code install the following packages

ng add @ng-bootstrap/ng-bootstrap

Then open styles.css and import bootstrap in it.

@import '~bootstrap/dist/css/bootstrap.min.css';

Then open the angular.json file adds the bootstrap.css to it.

"styles": [

Note: if you make any changes in the angular.json file, you must restart your application.

Open the enviornment.ts file and add your API project localhost URL to it.

export const environment = {
  production: false,

Create a book model using the following command.

ng g class Book --type=model

Open the book.model.ts and paste the following code into it.

import { DecimalPipe } from "@angular/common";

export class Book {
    id: number = 0;
    name: string | undefined;
    price: DecimalPipe | undefined;
    createdDate: Date | undefined;

Create services by using the following command.

ng g service BookService

Add the book.service.ts following code to it.

export class BookService {

  constructor(private http: HttpClient) { }

  getAllBook(): Observable<Book[]> {
    return this.http.get<Book[]>(`${environment.apiUrl}/Books`);

  addBook(books: object): Observable<Object> {
    return`${environment.apiUrl}/Books/AddBook`, books);

  getBookById(id: number) {
    return this.http.get(`${environment.apiUrl}/Books/${id}`);

  editBook(id: number, books: object): Observable<Object> {
    return this.http.put(`${environment.apiUrl}/Books/UpdateBook/${id}`, books);

  deleteBook(id: number): Observable<Object> {
    return this.http.delete(`${environment.apiUrl}/Books/DeleteBook/${id}`);


Then create a new book-master component.

ng g c book-master

Open book-master.component.ts and add the following code into it.

import { Component, OnInit } from '@angular/core';
import { Book } from '../book.model';
import { BookService } from '../book.service';
import { ToastrService } from 'ngx-toastr';
import { NgForm } from '@angular/forms';
import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap';

  selector: 'app-book-master',
  templateUrl: './book-master.component.html',
  styleUrls: ['./book-master.component.css']
export class BookMasterComponent implements OnInit {

  books: Book[] | any;
  bookData: Book = new Book();
  editbookData: Book = new Book();
  display = "none";
  closeResult = '';

  constructor(private bookServices: BookService, private toastr: ToastrService, private modalService: NgbModal) { }

  ngOnInit(): void {

  //Open Modal
  open(content: any, id: number) {
    this.bookServices.getBookById(id).subscribe((result: any) => {
      this.editbookData = result
    }), { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;

  //Dismiss Modal
  private 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}`;

  //Book List
  getBooksList() {
    this.bookServices.getAllBook().subscribe((book: any) => {
      this.books = book;

  //Save Book Function
  SaveBooks(addBookForm: NgForm) {
    this.bookServices.addBook(this.bookData).subscribe((result: any) => {
      if (result != null) {
        this.toastr.success('Submited successfuly', 'Book added successfuly');
      else {
        this.toastr.error('Something went wrong');

  //Delete Books Data
  DeleteBooks(id: number) {
    this.bookServices.deleteBook(id).subscribe((result: any) => {
      this.toastr.error('Deleted successfuly', 'Book delete successfuly');

  //Update Books Data
  updateBooks() {
    this.bookServices.editBook(, this.editbookData).subscribe((result: any) => {'Updated successfuly', 'Book updated successfuly');

Open book-master.component.html and add the following code to it.

<div class="container">
    <div class="row">
        <div class="col-md-4">
            <h3 class="text-center">Add Book</h3>
            <!-- Inserts a new record in the BookInfo collection -->
            <form (ngSubmit)="addBookForm.valid && SaveBooks(addBookForm)" #addBookForm="ngForm" novalidate>
                <div class="form-group">
                    <label for="txtName">Name:</label>
                    <input class="form-control" placeholder="Enter name" name="txtName" #txtName="ngModel" [(ngModel)]="" 
                      required [ngClass]="{'invalid-data': txtName.invalid && addBookForm.submitted, 'valid-data': txtName.valid && addBookForm.submitted}">
                    <div *ngIf="txtName.invalid && addBookForm.submitted " class="text-danger">
                <div class="form-group">
                    <label for="txtPrice">Price:</label>
                    <input type="number" class="form-control" placeholder="Enter price" name="txtPrice" #txtPrice="ngModel" [(ngModel)]="bookData.price"
                    required [ngClass]="{'invalid-data': txtPrice.invalid && addBookForm.submitted, 'valid-data': txtPrice.valid && addBookForm.submitted}">
                    <div *ngIf="txtPrice.invalid && addBookForm.submitted " class="text-danger">
                <button type="submit" class="btn btn-primary">Submit</button>
        <!-- BookInfo  List -->
        <div class="col-md-8">
            <h3 class="text-center">Book List</h3>
            <table class="table table-bordered">
                <thead class="thead-dark">
                        <th>Created Date</th>
                    <tr *ngFor="let book of books">
                        <td><button type="button" class="btn btn-default" (click)="open(content,">Edit</button>|
                            <button type="button" class="btn btn-default" (click)="DeleteBooks(">Delete</button></td>

<!-- Edit Modal -->
<ng-template #content let-modal>
    <div class="modal-header">
        <h4 class="modal-title" id="modal-basic-title">book update</h4>
        <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
    <div class="modal-body">
            <!-- Modal body -->
            <div class="modal-body">
                <input type="hidden" name="txtEId" [(ngModel)]="">
                <div class="form-group">
                    <label for="txtEName">Name:</label>
                    <input class="form-control" placeholder="Enter name" #txtEName="ngModel" name="txtEName" required [(ngModel)]="">
                    <div *ngIf="txtEName.invalid" class="text-danger">
                <div class="form-group">
                    <label for="txtEPrice">Price:</label>
                    <input type="number" class="form-control" placeholder="Enter price" #txtEPrice="ngModel" name="txtEPrice" required [(ngModel)]="editbookData.price">
                    <div *ngIf="txtEPrice.invalid" class="text-danger">
            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary" (click)="updateBooks()">Update</button>
                <button type="button" class="btn btn-danger" (click)="modal.close('Cancel click')">Cancel</button>
<!-- Edit Modal -->

Open app.module.ts add the following code to it.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { BookMasterComponent } from './book-master/book-master.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ToastrModule } from 'ngx-toastr';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

That’s it


Also check, ngx-Datatable in Angular 12

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories