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.
-
Update the file
src/app/task.service.ts
.import { Injectable, inject } from "@angular/core";@Injectable({providedIn: "root",})export class TaskService {tasks: WritableSignal<Task[]> = signal([{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 {this.tasks.update((tasks) => {return tasks.filter((task) => task.id !== id);});}}
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.