Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 74 ยท Projects

Project: Todo App with Signals

Build a todo app in Angular with a signal-based store, computed filters, small presentational components and persistence, plus runnable stand-ins for the logic and the UI.

A todo list is small enough to finish in an afternoon and rich enough to use most of what you have learned: components, inputs and outputs, signals, computed(), control flow, services and a little persistence. In this project you will design the app first, write the real Angular code, and then run the same ideas in the browser.

The plan has four steps: decide what the data and the screen are, put all state in one signal-based store, build two small components on top of it, and add persistence safely. You should be comfortable with Signals: signal, computed and effect, Inputs and Outputs and State Management with Signals and Services before you start.

Real versus stand-in. The typescript blocks are the real Angular app, written to be read and copied into a project created with ng new; the site cannot compile Angular. The runnable examples are stand-ins: one runs the store logic, including persistence, in TypeScript on a hand-written mini signal implementation, and one runs a working todo UI in plain JavaScript on the same kind of signals.

Step 1: the plan

  • A todo has an id, a title and a done flag.
  • The app state is the list of todos and the current filter: all, active or done.
  • The screen has a text box to add a todo, a list, a "N items left" count, filter buttons and a "Clear completed" button.
  • Derived values (the visible list, the counts) are computed, never stored.
flowchart TD
  P["TodoPage (smart)<br/>injects TodoStore"] --> I["TodoItem (presentational)<br/>input: todo<br/>outputs: toggle, remove"]
  P --> S["TodoStore (service)<br/>todos signal, filter signal<br/>computed: visible, remaining"]
  S --> L["localStorage<br/>(effect saves, constructor loads)"]

One page component talks to the store; one small component per row only displays and reports.

Step 2: the model and the store

Keep the data type in its own file and the logic in a service. The store owns two private signals and exposes read-only computed values and methods that describe intent:

TypeScript
// todo.model.ts
export interface Todo {
  id: number;
  title: string;
  done: boolean;
}

export type Filter = 'all' | 'active' | 'done';
TypeScript
// todo-store.ts
import { computed, effect, Injectable, signal } from '@angular/core';
import { Filter, Todo } from './todo.model';

const STORAGE_KEY = 'todos-v1';

@Injectable({ providedIn: 'root' })
export class TodoStore {
  private readonly items = signal<Todo[]>(this.load());
  private readonly currentFilter = signal<Filter>('all');
  private nextId = Math.max(0, ...this.items().map(t => t.id)) + 1;

  readonly filter = this.currentFilter.asReadonly();
  readonly remaining = computed(() => this.items().filter(t => !t.done).length);
  readonly hasDone = computed(() => this.items().some(t => t.done));
  readonly visible = computed(() => {
    const filter = this.currentFilter();
    return this.items().filter(t =>
      filter === 'all' ? true : filter === 'done' ? t.done : !t.done,
    );
  });

  constructor() {
    effect(() => this.save(this.items()));
  }

  add(title: string): void {
    const clean = title.trim();
    if (!clean) return;
    this.items.update(list => [...list, { id: this.nextId++, title: clean, done: false }]);
  }

  toggle(id: number): void {
    this.items.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
  }

  remove(id: number): void {
    this.items.update(list => list.filter(t => t.id !== id));
  }

  clearDone(): void {
    this.items.update(list => list.filter(t => !t.done));
  }

  setFilter(filter: Filter): void {
    this.currentFilter.set(filter);
  }

  private load(): Todo[] {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      return raw ? parseTodos(raw) : [];
    } catch {
      return []; // no storage (private mode, server rendering): start empty
    }
  }

  private save(list: Todo[]): void {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
    } catch {
      /* ignore: the app still works without persistence */
    }
  }
}

A few design choices are worth noticing. The writable signals are private, so every change goes through a method. Each update builds a new array, so signals notice it. The visible, remaining and hasDone values are computed(), so they are recalculated only when the list or filter changes and can never get out of sync with the data. The effect in the constructor is the one place where we need a side effect: saving whenever the list changes.

Persistence needs care. Data from localStorage is text that any older version of your app, or the user, could have changed. Parse it defensively and drop anything that is not a valid todo:

TypeScript
export function parseTodos(raw: string): Todo[] {
  let data: unknown;
  try {
    data = JSON.parse(raw);
  } catch {
    return [];
  }
  if (!Array.isArray(data)) return [];
  return data.filter(
    (t): t is Todo =>
      typeof t === 'object' && t !== null &&
      typeof t.id === 'number' && typeof t.title === 'string' && typeof t.done === 'boolean',
  );
}

The try/catch also covers server-side rendering, where localStorage does not exist (SSR, Hydration and Prerendering). Versioning the key (todos-v1) lets you change the format later without breaking old data.

Step 3: the components

The row component is purely presentational: it receives a todo and reports two events.

TypeScript
// todo-item.ts
import { Component, input, output } from '@angular/core';
import { Todo } from './todo.model';

@Component({
  selector: 'app-todo-item',
  template: `
    <li [class.done]="todo().done">
      <label>
        <input type="checkbox" [checked]="todo().done" (change)="toggle.emit()" />
        {{ todo().title }}
      </label>
      <button type="button" (click)="remove.emit()" [attr.aria-label]="'Delete ' + todo().title">
        Delete
      </button>
    </li>
  `,
  styles: `.done label { text-decoration: line-through; opacity: 0.6; }`,
})
export class TodoItem {
  todo = input.required<Todo>();
  toggle = output<void>();
  remove = output<void>();
}

The page is the smart component. It injects the store, shows the list with @for and track, and handles the form:

TypeScript
// todo-page.ts
import { Component, inject } from '@angular/core';
import { TodoItem } from './todo-item';
import { Filter } from './todo.model';
import { TodoStore } from './todo-store';

@Component({
  selector: 'app-todo-page',
  imports: [TodoItem],
  template: `
    <h1>Todos</h1>

    <input #box aria-label="New todo" placeholder="What needs doing?"
           (keydown.enter)="add(box)" />
    <button type="button" (click)="add(box)">Add</button>

    <div role="group" aria-label="Filter">
      @for (f of filters; track f) {
        <button type="button" [attr.aria-pressed]="store.filter() === f"
                (click)="store.setFilter(f)">{{ f }}</button>
      }
    </div>

    <ul>
      @for (todo of store.visible(); track todo.id) {
        <app-todo-item [todo]="todo"
                       (toggle)="store.toggle(todo.id)"
                       (remove)="store.remove(todo.id)" />
      } @empty {
        <li>Nothing here yet.</li>
      }
    </ul>

    <p>{{ store.remaining() }} {{ store.remaining() === 1 ? 'item' : 'items' }} left</p>
    @if (store.hasDone()) {
      <button type="button" (click)="store.clearDone()">Clear completed</button>
    }
  `,
})
export class TodoPage {
  protected readonly store = inject(TodoStore);
  protected readonly filters: Filter[] = ['all', 'active', 'done'];

  protected add(box: HTMLInputElement): void {
    this.store.add(box.value);
    box.value = '';
  }
}

Three things to notice. track todo.id lets Angular keep the same row element for the same todo, so toggling does not rebuild the list (Control Flow: @if, @for and @switch). The @empty block handles the no-results case. And the buttons use aria-pressed and aria-label so the app works with a screen reader (Security and Accessibility). Add <app-todo-page /> to your root component's template and import TodoPage there.

Step 4: run the logic

The first stand-in runs the whole store on a tiny signal implementation, with a Map playing the part of localStorage. It shows adding, toggling, the three filters, saving, a "reload" that creates a second store from the saved data, and loading corrupted data.

TypeScript The todo store: logic and persistence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check the result against the design. A blank title never reaches the list. The effect saves once for the initial state and once per change to the list (six saves in this run), and filter changes do not save at all. The reloaded store continues the id sequence instead of reusing an id. Invalid saved entries are dropped without crashing, and unreadable JSON gives an empty list.

Step 5: see it as a UI

The second stand-in is a complete todo UI in plain JavaScript. It uses the same signals idea: three effect() calls re-render the count, the filter buttons and the list whenever the signals they read change. Real Angular updates only the parts of the DOM that changed; this stand-in rebuilds the list for simplicity, so keyboard focus does not stay on a checkbox after you toggle it. The sandbox forbids localStorage, so the data lives in memory.

A working todo UI built on signals

Try adding a todo, completing one, switching the filter and clearing completed items. Notice that the third todo contains HTML-looking text and is displayed as plain text, because the stand-in assigns textContent. Angular's {{ todo().title }} does the same, which is why interpolation is safe by default.

Ideas to extend it

  • Edit a title in place by double-clicking, with an editing signal in the row component.
  • Add an aria-live region that announces "Todo added".
  • Store the filter in the URL as a query parameter (Route Parameters, Query Params and Navigation).
  • Replace the local store with an HttpClient service later; the components would not change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are visible and remaining defined with computed() instead of stored in their own signals?

    Derived values should be computed from the source of truth. Storing them separately invites bugs where they disagree with the data.
  2. 2. Why does the store call items.update() with a new array instead of pushing into the existing one?

    Signals compare with Object.is. A mutated array is the same object, so dependents would not update.
  3. 3. What should you do with data you read back from localStorage?

    Stored text can be corrupted, edited or written by an older version of the app. Validate it and fall back to an empty list.
  4. 4. What does the TodoItem component not do?

    It is presentational. The smart page component owns the store and responds to the outputs, which keeps TodoItem reusable and easy to test.
  5. 5. What is the purpose of track todo.id in the @for block?

    Tracking by a stable identity means that reordering, adding and removing only touch the affected rows.

Summary

  • Model the data first (Todo, Filter), then keep all state in one service with private writable signals and intent-revealing methods.
  • Derive everything else with computed(): the visible list, the remaining count and whether anything is done.
  • Update immutably, validate persisted data when you load it, and use one effect() for saving.
  • Split the UI into a smart page that injects the store and a presentational row that uses input() and output().
  • Use @for with track, @empty, aria-pressed and labels for a fast, accessible list.

Next: Project: Weather Dashboard with HttpClient.