Add a Delete Function
Chapter Objectives
- Add a delete function
Learn how to add a function to remove tasks 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.
-
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.