To-do List with Signals - Mini Project

To-Do List Using Angular Signals

In this part, a simple To-Do List is created using Angular signals to practice how signals work in a real example.

The goal is to add tasks, display them in a list, and delete tasks using signals.


Task Signal Setup

A signal named tasks is created to store the list of tasks.

Each task is an object with id, title, and completed properties.

tasks = signal([
{ id: 0, title: "Team lunch", completed: false }
])

A separate signal is created to store the input value for a new task title.

title = signal('')


Displaying the Task List

The task list is shown using Angular control flow with @for.

Since tasks is a signal, it is accessed using tasks().

<ul>
@for(task of tasks(); track task.id){
<li class="task-list">
<span>{{$index + 1}}</span>
<span>{{ task.title }}</span>
<span>
<button (click)="deleteTask(task.id)">delete</button>
</span>
</li>
}
@empty{
<span>No Task found</span>
}
</ul>

If there are no tasks, “No Task found” is displayed using @empty.


Adding a New Task

An input field is used to type a task title.

The value is taken from the title signal.

<input
type="text"
[value]="title()"
(input)="title.set($event.target.value)"
placeholder="enter task"
>
<button (click)="addTask()">Add Task</button>

The addTask() function adds a new task to the signal array.


addTask() {
if (this.title()) {
this.tasks.update(item => (
[...item, {
id: this.tasks().length,
title: this.title(),
completed: false
}]
))
this.title.set('');
}
}

Empty tasks are not added because of the if (this.title()) check.

After adding a task, the input field is cleared.


Deleting a Task

Each task has a delete button.

The task id is passed to the delete function.

deleteTask(id: number) {
this.tasks.update(tasks =>
tasks.filter(task => task.id != id)
)
}

The task is removed by filtering out the matching id.


Important Points

Tasks are stored in an array signal.

update() is used to add and remove tasks from the signal.

Signals are always accessed using () in the template.

Empty input values are prevented from being added.

@empty is used to show a message when the task list is empty.