To finalize the coding part of the series, we are going to implement the logic for deleting the entity. To do that, we are going to create a form to support this action and send the DELETE request to our server.

For the complete navigation and all the basic instructions of the Angular series, check out: Introduction of the Angular series.

To download the source code for this article, you can visit our GitHub repository.

So, let’s dive right into it.

Folder Structure and Routing

Let’s start by executing the Angular CLI command, which is going to create the required folder structure. Moreover, it is going to import the OwnerDelete component inside the owner.module.ts file:

ng g component owner/owner-delete --skip-tests

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

In addition, we have to modify the owner-routing.module.ts file to enable routing for this component:

const routes: Routes = [
  { path: 'list', component: OwnerListComponent },
  { path: 'details/:id', component: OwnerDetailsComponent },
  { path: 'create', component: OwnerCreateComponent },
  { path: 'update/:id', component: OwnerUpdateComponent },
  { path: 'delete/:id', component: OwnerDeleteComponent }
];

Furthermore, let’s modify the owner-list.component.html file:

<td><button type="button" id="delete" class="btn btn-danger"
  (click)="redirectToDeletePage(owner.id)">Delete</button></td>

And the owner-list.component.ts file to enable navigation to the delete page:

public redirectToDeletePage = (id) => { 
  const deleteUrl: string = `/owner/delete/${id}`; 
  this.router.navigate([deleteUrl]); 
}

Prepare the Page for Angular Delete Actions

To create the HTML part of the component, let’s start with the wrapper code:

<div class="container">
  <div class="row">
    <div class="col-md-10 card card-body bg-light mb-2 mt-2">
      
    </div>
  </div>
</div>

Inside the div element with the col-md-10 class, we are going to show all the details from the entity we want to delete:

<div class="row">
  <div class="col-md-3">
    <label for="name" class="control-label">Owners name:</label>
  </div>
  <div class="col-md-7">
    <span name="name">
      {{owner?.name}}
    </span>
  </div>
</div>

<div class="row">
  <div class="col-md-3">
    <label for="dateOfBirth" class="control-label">Date of birth:</label>
  </div>
  <div class="col-md-7">
    <span name="dateOfBirth">
      {{owner?.dateOfBirth | date: 'MM/dd/yyyy'}}
    </span>
  </div>
</div>

<div class="row">
  <div class="col-md-3">
    <label for="address" class="control-label">Address:</label>
  </div>
  <div class="col-md-7">
    <span name="address">
      {{owner?.address}}
    </span>
  </div>
</div>

Right below the last div element, let’s add the buttons:

<br>
<div class="row">
  <div class="offset-md-3 col-md-1">
    <button type="submit" class="btn btn-info" (click)="deleteOwner()">Delete</button>
  </div>
  <div class="col-md-1">
    <button type="button" class="btn btn-danger" (click)="redirectToOwnerList()">Cancel</button>
  </div>
</div>

<span style="font-family: Georgia, 'times new roman', 'bitstream charter', Times, serif;">That's it.</span>

Our HTML part of the component is ready. All we have to do is to implement the business logic.

Handling Angular Delete Actions in the Component File

Let’s start with the import statements in the owner-delete.copmonent.ts file:

import { HttpErrorResponse } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { ErrorHandlerService } from './../../shared/services/error-handler.service';
import { OwnerRepositoryService } from './../../shared/services/owner-repository.service';
import { Owner } from './../../_interfaces/owner.model';
import { Component, OnInit } from '@angular/core';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap/modal';
import { SuccessModalComponent } from 'src/app/shared/modals/success-modal/success-modal.component';

Then, let’s create necessary properties and inject services in the constructor:

export class OwnerDeleteComponent implements OnInit {
  owner: Owner;
  bsModalRef?: BsModalRef;

  constructor(private repository: OwnerRepositoryService, private errorHandler: ErrorHandlerService,
    private router: Router, private activeRoute: ActivatedRoute, private modal: BsModalService) { }
}

Bellow the constructor, we are going to add the logic for fetching the owner and redirecting to the owner-list component:

ngOnInit(): void {
  this.getOwnerById();
}

private getOwnerById = () => {
  const ownerId: string = this.activeRoute.snapshot.params['id'];
  const apiUri: string = `api/owner/${ownerId}`;

  this.repository.getOwner(apiUri)
  .subscribe({
    next: (own: Owner) => this.owner = own,
    error: (err: HttpErrorResponse) => this.errorHandler.handleError(err)
  })
}

redirectToOwnerList = () => {
  this.router.navigate(['/owner/list']);
}

Everything here is familiar from our previous posts.

Finally, let’s implement the delete logic right below the redirectToOwnerList function:

deleteOwner = () => {
  const deleteUri: string = `api/owner/${this.owner.id}`;

  this.repository.deleteOwner(deleteUri)
  .subscribe({
    next: (_) => {
      const config: ModalOptions = {
        initialState: {
          modalHeaderText: 'Success Message',
          modalBodyText: `Owner deleted successfully`,
          okButtonText: 'OK'
        }
      };

      this.bsModalRef = this.modal.show(SuccessModalComponent, config);
      this.bsModalRef.content.redirectOnOk.subscribe(_ => this.redirectToOwnerList());
    },
    error: (err: HttpErrorResponse) => this.errorHandler.handleError(err)
  })
}

That is it. We have finished our Angular part of this application. As a result, we have a fully functional application ready for deployment. Therefore, all we have left to do is to prepare Angular files for production and deploy the completed application.

Conclusion

By reading this post you have learned:

  • How to create the HTML part of the delete action
  • How to send the DELETE request to the server

In the next part of the series, we are going to publish this complete application in the Windows environment by using the IIS.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!