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

Prerequisites:

  • 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": [
            "node_modules/bootstrap/dist/css/bootstrap.min.css",
            "src/styles.css",
            "node_modules/ngx-toastr/toastr.css"
          ],

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,
  apiUrl:"https://localhost:44309/api"
};

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 this.http.post(`${environment.apiUrl}/Books/AddBook`, books);
  }

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

  editBook(id: number, books: object): Observable<Object> {
    debugger  
    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';


@Component({
  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 {
    this.getBooksList();
  }

  //Open Modal
  open(content: any, id: number) {
    this.bookServices.getBookById(id).subscribe((result: any) => {
      this.editbookData = result
    })
    this.modalService.open(content, { 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 {
    debugger
    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) {
        addBookForm.resetForm();
        this.toastr.success('Submited successfuly', 'Book added successfuly');
        this.getBooksList();
      }
      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');
      this.getBooksList();
    })
  }

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

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)]="bookData.name" 
                      required [ngClass]="{'invalid-data': txtName.invalid && addBookForm.submitted, 'valid-data': txtName.valid && addBookForm.submitted}">
                    <div *ngIf="txtName.invalid && addBookForm.submitted " class="text-danger">
                        Required
                    </div>
                </div>
                <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">
                        Required
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
        <!-- BookInfo  List -->
        <div class="col-md-8">
            <h3 class="text-center">Book List</h3>
            <table class="table table-bordered">
                <thead class="thead-dark">
                    <tr>
                        <th>Name</th>
                        <th>Price</th>
                        <th>Created Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let book of books">
                        <td>{{book.name}}</td>
                        <td>{{book.price}}</td>
                        <td>{{book.createdDate|date:'mediumDate'}}</td>
                        <td><button type="button" class="btn btn-default" (click)="open(content,book.id)">Edit</button>|
                            <button type="button" class="btn btn-default" (click)="DeleteBooks(book.id)">Delete</button></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 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>
      </button>
    </div>
    <div class="modal-body">
        <form>
            <!-- Modal body -->
            <div class="modal-body">
                <input type="hidden" name="txtEId" [(ngModel)]="editbookData.id">
                <div class="form-group">
                    <label for="txtEName">Name:</label>
                    <input class="form-control" placeholder="Enter name" #txtEName="ngModel" name="txtEName" required [(ngModel)]="editbookData.name">
                    <div *ngIf="txtEName.invalid" class="text-danger">
                        Required
                    </div>
                </div>
                <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">
                        Required
                    </div>
                </div>
            </div>
            <!-- 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>
            </div>
        </form>
    </div>
</ng-template>
<!-- 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';

@NgModule({
  declarations: [
    AppComponent,
    BookMasterComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule,
    HttpClientModule,
    FormsModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

That’s it

Output.

Also check, ngx-Datatable in Angular 12

Submit a Comment

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

Subscribe

Select Categories