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.
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
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.
hi another problem is that you disabled the save insert and delete buttons but never enabled them i enabled the, but they dont seem to work
This is very strange and weird at least. I really do not remember disabling these buttons and again if you inspect the source code of the owner-list.html file you will see this:
<tbody>
<tr *ngFor=”let owner of owners”>
<td>{{owner.name}}</td>
<td>{{owner.address}}</td>
<td>{{owner.dateOfBirth | date: ‘dd/MM/yyyy’}}</td>
<td><button type=”button” id=”details” class=”btn btn-primary”
(click)=”getOwnerDetails(owner.id)”>Details</button></td>
<td><button type=”button” id=”update” class=”btn btn-success”
(click)=”redirectToUpdatePage(owner.id)”>Update</button></td>
<td><button type=”button” id=”delete” class=”btn btn-danger”
(click)=”redirectToDeletePage(owner.id)”>Delete</button></td>
</tr>
</tbody>
So for each entity in the array, we display a new owner on the page with all the buttons enabled.
And they all work, they have to, I’ve tested this app so many times, and as you can see, I even updated it to Angular 13. So there is no way that I would update the article and the code without checking if it is working.
hi as i run the code for the last time it gives the error
Error: src/app/owner/owner-update/owner-update.component.ts:74:39 – error TS2345: Argument of type ‘OwnerUpdateInterface’ is not assignable to parameter of type ‘Owner’.
Property ‘id’ is missing in type ‘OwnerUpdateInterface’ but required in type ‘Owner’.
74 this.repository.updateOwner(apiUri, ownerForUpd)
~~~~~~~~~~~
src/app/_interfaces/owner.model.ts:3:3
3 id: string;
~~
‘id’ is declared here.
× Failed to compile.
like the error is that id is declared in owner module but not in owner update
Regarding this issue. If you carefully read our Update article (the previous one) you could find a place where we create the OwnerForUpdate interface and immediately modify the repository to accept this interface as a parameter instead of the Owner interface. If you do that, you won’t be getting this error, or at least I assume. We have provided our source code for each article so it is always a good practice to download it and compare it with yours.
Hi Marinko,
I have read ASP.NET CORE SERIES, I followed all the steps, but I think there is something missed in series if I’m right, and that is User authentication. It would be good if series contains Toke based authentication.
Although series is very helpful.
Thank you
Qamar
Hello Qamar. Thank you for your comment and suggestion. But please take a look at this article (http://34.65.74.140/authentication-aspnetcore-jwt-1/) this is a first part and in it you can find a link towards the second part. In there you will find well explained how to use token based authentication and authorization with .net core and angular. All the best.
Oh, Yes there is.
Sorry I missed it.
Thank you.
Hi Marinko,
Your article is like developer help books to beginner like me. I follow all the steps and able to create application. Can you add few more article in the series to flow like display list with edit delete buttons and based on edit delete show forms as well as for create seprate form.
May be models for create and update.
It will really help to us.
Thanks you.
Omkar.
Good Work