Skip to content

Add a delete function to TaskService

Chapter Objectives

  • ✔️
    Handle Deletion
    Learn how to delete a task from the list.

The deleteTask function

To delete a task from the list, let’s create a deleteTask function in the TaskService. This function will remove the task from the list based on its id.

🎓 Instructions

  1. Modify the file src/app/task.service.ts.

    import { Injectable } from "@angular/core";
    @Injectable({
    providedIn: "root",
    })
    export class TaskService {
    tasks: Task[] = [
    {
    id: uuid(),
    title: "Task 1",
    description: "Description of task 1",
    createdAt: new Date(),
    },
    {
    id: uuid(),
    title: "Task 2",
    description: "Description of task 2",
    createdAt: new Date(),
    },
    ];
    deleteTask(id: string): void {
    const taskIndex = this.tasks.findIndex((task) => task.id === id);
    this.tasks.splice(taskIndex, 1);
    }
    }

✔️ What you’ve learned

In this chapter, you’ve added a function that allows you to delete a task from the list based on its id in the TaskService.