Add a Delete Button
- Add a delete button
Learn how to add a button to remove tasks from the list.
The delete button
Section titled “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.
A click event is sufficient here because delete is a simple direct action that doesn’t involve form submission, validation, or keyboard interaction - it’s just a single button performing one specific task.
-
Update the file
src/app/task-list/task-list.html
.task-list.html <tbody>@for (task of tasks(); track task.id) {<tr><td>{{ task.title }}</td><td>{{ task.createdAt | date}}</td><td><a class="btn btn-secondary" [routerLink]="['/update', task.id]">Update</a><button class="btn btn-danger" type="button" (click)="deleteTask(task.id)">Delete</button></td></tr>}</tbody>
The deleteTask function
Section titled “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.
-
Update the file
src/app/task-list/task-list.ts
.import {Component, inject} from '@angular/core';import {DatePipe} from "@angular/common";import {TaskService} from '../task-service';import {RouterLink} from '@angular/router';@Component({selector: 'app-task-list',imports: [DatePipe,RouterLink],templateUrl: './task-list.html',styleUrl: './task-list.css'})export class TaskList {private taskService = inject(TaskService);tasks: Task[] = this.taskService.tasks;deleteTask(id: string): void {this.taskService.deleteTask(id);}}
Let’s test it!
Section titled “Let’s test it!”- Click the delete button next to a task in the list. 2. This task should be removed from the list.
In this chapter, you added a function to delete a task.