Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 74 ยท Projects

Project: Expense Tracker with Services and localStorage

Build an expense tracker in Angular with a signal-based service, money stored in cents, category filters, totals and safe localStorage persistence, with runnable stand-ins.

An expense tracker is a classic first "real" app because it has a clear data model, a few derived numbers (totals, per-category sums) and a need to remember data between visits. It also hides one famous trap: money and floating-point numbers do not mix well. We will handle that properly.

This project builds on State Management with Signals and Services and the persistence ideas of the Todo project. The design has four steps: model the data, write one signal service, build the screen, and persist safely.

Real versus stand-in. The typescript blocks are the real Angular app, to read and copy into a project made with ng new. The site cannot compile Angular and its sandbox has no localStorage, so the runnable examples are stand-ins: one runs the service logic in TypeScript with a Map instead of storage, and one is a working UI in plain JavaScript that keeps data in memory.

Step 1: the plan

  • An expense has an id, a title, an amountCents (an integer), a category and a date (YYYY-MM-DD).
  • The user can add and delete expenses and filter by category.
  • Derived values: the visible list, the total of the visible list, and the total per category.

Why cents? In JavaScript 0.1 + 0.2 is 0.30000000000000004. Adding many prices as decimals drifts. Store whole cents as integers, add integers, and format only when you display. The form converts what the user types (12.50) into 1250 once, at the edge.

flowchart TD
  F["Form: title, amount, category"] --> V["parseAmount()<br/>12.50 to 1250 cents"]
  V --> S["ExpenseStore (signals)"]
  S --> C["computed: visible, total, byCategory"]
  S --> L["localStorage<br/>load in constructor, save in effect"]
  C --> T["Template"]

The form converts once at the edge; everything inside the store is integers.

Step 2: the model and helper functions

TypeScript
// expense.ts
export type Category = 'food' | 'transport' | 'home' | 'fun';
export const CATEGORIES: Category[] = ['food', 'transport', 'home', 'fun'];

export interface Expense {
  id: number;
  title: string;
  amountCents: number;
  category: Category;
  date: string;
}

/** "12.50" -> 1250. Returns null for anything that is not a positive amount. */
export function parseAmount(text: string): number | null {
  const match = /^(\d{1,9})(?:[.,](\d{1,2}))?$/.exec(text.trim());
  if (!match) return null;
  const cents = Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0'));
  return cents > 0 ? cents : null;
}

export function formatMoney(cents: number): string {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(cents / 100);
}

parseAmount accepts 12, 12.5 and 12,50 but rejects abc, -3, 0 and 1.234. Using Intl.NumberFormat at display time (or Angular's currency pipe, see Pipes) keeps formatting out of the data.

Step 3: the store

TypeScript
// expense-store.ts
import { computed, effect, Injectable, signal } from '@angular/core';
import { Category, Expense } from './expense';

const KEY = 'expenses-v1';

@Injectable({ providedIn: 'root' })
export class ExpenseStore {
  private readonly items = signal<Expense[]>(this.load());
  private readonly categoryFilter = signal<Category | 'all'>('all');
  private nextId = Math.max(0, ...this.items().map(e => e.id)) + 1;

  readonly filter = this.categoryFilter.asReadonly();
  readonly visible = computed(() => {
    const f = this.categoryFilter();
    return this.items().filter(e => f === 'all' || e.category === f);
  });
  readonly total = computed(() => this.visible().reduce((sum, e) => sum + e.amountCents, 0));
  readonly byCategory = computed(() => {
    const sums = new Map<Category, number>();
    for (const e of this.items()) sums.set(e.category, (sums.get(e.category) ?? 0) + e.amountCents);
    return sums;
  });

  constructor() {
    effect(() => {
      try {
        localStorage.setItem(KEY, JSON.stringify(this.items()));
      } catch {
        /* storage unavailable: keep working in memory */
      }
    });
  }

  add(input: Omit<Expense, 'id'>): void {
    this.items.update(list => [...list, { ...input, id: this.nextId++ }]);
  }

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

  setFilter(value: Category | 'all'): void {
    this.categoryFilter.set(value);
  }

  private load(): Expense[] {
    try {
      const raw = localStorage.getItem(KEY);
      return raw ? parseExpenses(raw) : [];
    } catch {
      return [];
    }
  }
}

export function parseExpenses(raw: string): Expense[] {
  let data: unknown;
  try {
    data = JSON.parse(raw);
  } catch {
    return [];
  }
  if (!Array.isArray(data)) return [];
  return data.filter(
    (e): e is Expense =>
      typeof e === 'object' && e !== null &&
      Number.isInteger(e.amountCents) && e.amountCents > 0 &&
      typeof e.id === 'number' && typeof e.title === 'string' &&
      typeof e.category === 'string' && typeof e.date === 'string',
  );
}

The total is computed() from the visible list, so changing the filter updates both without any extra code. As with every store in this tutorial, the writable signal stays private, each change builds a new array, and loading validates what it reads, since stored text may be old, edited or corrupted. The try/catch also protects server rendering, where localStorage does not exist (SSR, Hydration and Prerendering).

Step 4: the page

TypeScript
// expense-page.ts
import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { CATEGORIES, Category, parseAmount } from './expense';
import { ExpenseStore } from './expense-store';

@Component({
  selector: 'app-expense-page',
  imports: [ReactiveFormsModule, CurrencyPipe],
  template: `
    <form [formGroup]="form" (ngSubmit)="add()">
      <input formControlName="title" aria-label="Title" placeholder="Coffee" />
      <input formControlName="amount" aria-label="Amount" inputmode="decimal" placeholder="3.50" />
      <select formControlName="category" aria-label="Category">
        @for (c of categories; track c) { <option [value]="c">{{ c }}</option> }
      </select>
      <button type="submit" [disabled]="form.invalid">Add</button>
    </form>

    <select aria-label="Filter" (change)="store.setFilter($any($event.target).value)">
      <option value="all">All categories</option>
      @for (c of categories; track c) { <option [value]="c">{{ c }}</option> }
    </select>

    <ul>
      @for (e of store.visible(); track e.id) {
        <li>{{ e.date }} {{ e.title }} <b>{{ e.amountCents / 100 | currency }}</b>
          <button type="button" (click)="store.remove(e.id)">Delete</button></li>
      } @empty { <li>No expenses yet.</li> }
    </ul>
    <p>Total: <b>{{ store.total() / 100 | currency }}</b></p>
  `,
})
export class ExpensePage {
  protected readonly store = inject(ExpenseStore);
  protected readonly categories = CATEGORIES;
  private readonly fb = inject(FormBuilder);

  protected readonly form = this.fb.nonNullable.group({
    title: ['', Validators.required],
    amount: ['', [Validators.required, c => (parseAmount(c.value) ? null : { amount: true })]],
    category: ['food' as Category],
  });

  protected add(): void {
    const { title, amount, category } = this.form.getRawValue();
    const cents = parseAmount(amount);
    if (!cents || !title.trim()) return;
    this.store.add({ title: title.trim(), amountCents: cents, category, date: new Date().toISOString().slice(0, 10) });
    this.form.reset({ title: '', amount: '', category });
  }
}

The amount control has a custom validator that reuses parseAmount, so the same rule guards the form and the store (Form Validation). Dividing by 100 happens only in the template, at display time.

Step 5: run the logic

This stand-in runs parseAmount, the store rules and persistence. A Map plays localStorage, and a plain class replaces signals so the output is easy to follow.

TypeScript Expense logic: cents, totals, 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.

Notice that three decimal prices add up exactly as cents, that 1.234 is rejected instead of silently rounded, and that corrupted saved data is filtered out instead of crashing the app.

Step 6: see it as a UI

The UI stand-in keeps the same rules. It stores data in memory because the sandbox blocks localStorage.

A working expense tracker UI

Ideas to extend it

  • Filter by month with a second signal and a computed() over date.
  • Show a bar per category using byCategory().
  • Export the list as CSV with a Blob and an <a download> link.
  • Move the storage code behind an injection token so tests can supply a fake (Providers and Injection Tokens).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the app store amounts as integer cents?

    Binary floating point cannot represent most decimal fractions exactly. Adding whole cents is exact, and you divide by 100 only for display.
  2. 2. Where should the conversion from "12.50" to 1250 happen?

    Convert and validate input at the boundary. Everything inside the store then works with clean integers.
  3. 3. What do total and byCategory depend on?

    They are computed() values. When the signals they read change, they recalculate; no manual syncing is needed.
  4. 4. Why does the store wrap localStorage calls in try/catch?

    Persistence is a bonus. When it is unavailable the app keeps working in memory.

Summary

  • Store money as integer cents, convert at the input edge, and format only for display.
  • Keep one signal store with a private writable list, derived totals via computed(), and an effect() that saves.
  • Validate saved data when loading and guard storage calls with try/catch.
  • Reuse the same parseAmount rule in the form validator and in the store.
  • Derive per-category sums instead of keeping extra state.

Next: Project: Snake Game on a Canvas.