Angular CRUD 5: Delete

This is the fifth and final post dedicated to performing CRUD operations in Angular and it’s focus will be on adding the ability to delete a villain.

The completed solution can be found on GitHub.

Adding the delete functionality

The changes are within the list-villains component and the first task is to add the delete button. This is done using the following code which is added to list-villains.component.html

...
<td><button type="button" class="btn btn-danger" (click)="deleteVillain(villain.id, villain.name, villain.episode)">Delete</button></td>
...

The button’s click listener calls the new method deleteVillain passing to it the details of the villain selected.

The deleteVillain method has been added to list-villains.component.ts

 deleteVillain(id: string, name: string, episode: string ) {   
    if(confirm("Do you wish to delete " + name)) {
      const villain = { id: +id, name: name, episode: episode };
      this.villainService.deleteVillain(villain).subscribe();  
      this.getVillains();
    }    
  }

This method displays the default browser confirmation dialogue showing a message to the user confirming which villain they are about to delete.

If the user selects ok, a villain object is created using the supplied parameters. The object is then passed to the delete method of the villain service. The final step is to refresh the list of villains displayed.

Acknowledgements

The method used for displaying the confirmation dialogue is taken from this Stackoverflow answer.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.