Skip to content

Add delete button in the TaskListComponent

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

The delete button

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

🎓 Instructions

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

    <ul>
    <li *ngFor="let task of tasks; let i = index">
    Task name: {{ task.title }}
    <button type="button" (click)="deleteTask(task.id)">Delete</button>
    </li>
    </ul>

The deleteTask function

Let’s create the deleteTask function in the TaskListComponent class to remove a task from the list. It’ll call the deleteTask function from the TaskService class to remove the task from the list.

🎓 Instructions

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

    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 implements OnInit {
    tasks: Task[] = this.taskService.tasks;
    constructor(private taskService: TaskService) { }
    ngOnInit() {}
    deleteTask(uuid: string) {
    this.taskService.deleteTask(uuid);
    }
    }

Let’s test it out

  1. Click on the ‘Delete’ button next to a task in the list.
  2. The task should be removed from the list.

✔️ What you learned

You are now able to delete a task from the list from the TaskListComponent Component.