Skip to content

Add a delete button in TaskListComponent

Chapter Objectives

  • ✔️
    Delete a task
    Add a delete button in the TaskListComponent to remove the task from the list.

The delete button

Let’s modify the TaskListComponent to add a delete button next to each task in the list. When the user clicks this button, the task will be removed from the list.

🎓 Instructions

  1. Modify the file src/app/task-list/task-list.component.html.

    task-list.component.html
    <tr *ngFor="let task of tasks">
    <td>{{ task.title }}</td>
    <td>{{ task.createdAt | date }}</td>
    <td>
    <a class="btn btn-primary" [routerLink]="['/update', task.id]">Update</a>
    <button
    class="btn btn-danger"
    type="button"
    (click)="deleteTask(task.id)"
    >
    Delete
    </button>
    </td>
    </tr>

The deleteTask function

Let’s create a deleteTask function in the TaskListComponent to remove a task from the list. This function will call the deleteTask function of TaskService created in the previous chapter to remove a task from the list.

🎓 Instructions

  1. Modify the file src/app/task-list/task-list.component.ts.

    import { Component } from "@angular/core";
    import { TaskService } from "../task.service";
    @Component({
    selector: "app-task-list",
    templateUrl: "./task-list.component.html",
    styleUrls: ["./task-list.component.css"],
    })
    export class TaskListComponent {
    tasks: Task[] = this.taskService.tasks;
    constructor(private taskService: TaskService) {}
    deleteTask(id: string): void {
    this.taskService.deleteTask(id);
    }
    }

Let’s test it!

  1. Click the delete button next to a task in the list. 2. This task should be removed from the list.

✔️ What you have learned

In this chapter, you added a function to delete a task.