Skip to main content

Web frameworks · Intermediate · 30 min

Load data and handle forms in Angular 22

By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13 · Angular 22.3.0 · Angular CLI 22.3.0

You will have an Angular 22.3 expense tracker with two routes that loads expenses from a local JSON API with httpResource, shows loading and error states, and saves new expenses through a validated signal form and an interceptor that adds an Idempotency-Key header.

On this page

The first Angular tutorial kept its expenses in a signal, so they vanished when you refreshed the page. A real app reads its data from a server and writes changes back. That brings three new jobs: moving between screens, waiting for data that may fail to arrive, and checking what a person types before you send it.

Angular 22 has a first-party answer for each. The router maps URLs to components. httpResource turns an HTTP request into a set of signals (value, loading, error) that a template can read directly. Signal Forms, stable since Angular 22, builds a typed form from a signal and a list of validation rules. An interceptor sits in front of every request HttpClient sends, so a header you need everywhere is written once.

In this tutorial you build an expense tracker with two pages: a list with a running total, and a form to add an expense. It talks to a small JSON API you write in plain Node.js. The form sends an Idempotency-Key header so that tapping Save twice on a slow connection still creates one expense, not two.

You start a fresh project so your files match this page. Commands are for a Linux or macOS shell, or WSL on Windows. You need three terminals: one for the API, one for the Angular dev server and one for everything else.

Step 1 · Create the project and a local API

Create a new Angular 22.3 project. --defaults accepts the standard answers (CSS, no server-side rendering) and --skip-git keeps this throwaway demo out of version control; leave it off for a real project:

Bash
cd ~
npx @angular/cli@22.3.0 new expenses-data --defaults --skip-git
cd expenses-data

Now the API. Create api/server.mjs, a Node.js server with no dependencies. It keeps expenses in memory, waits half a second before every answer so you can see loading states, and refuses any POST without an Idempotency-Key header. When a key arrives that it has already seen, it returns the expense it saved the first time instead of saving a copy:

Bash
mkdir -p api
cat > api/server.mjs <<'JS'
import { createServer } from 'node:http'

const expenses = [
  { id: 3, description: 'Mobile data bundle', amount: 10, category: 'Data and airtime', date: '2026-11-08' },
  { id: 2, description: 'Bus fare', amount: 3.2, category: 'Transport', date: '2026-11-05' },
  { id: 1, description: 'Groceries', amount: 42.5, category: 'Food', date: '2026-11-03' },
]
let nextId = 4
const savedByKey = new Map()

function send(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
  res.end(JSON.stringify(body))
}

createServer(async (req, res) => {
  const url = new URL(req.url, 'http://localhost')
  const key = req.headers['idempotency-key']
  console.log(req.method, url.pathname, key ? `key=${key}` : '')
  await new Promise((resolve) => setTimeout(resolve, 500))

  if (url.pathname !== '/api/expenses') return send(res, 404, { error: 'Not found' })
  if (req.method === 'GET') return send(res, 200, expenses)
  if (req.method !== 'POST') return send(res, 405, { error: 'Method not allowed' })

  if (!key) return send(res, 400, { error: 'Idempotency-Key header is required' })
  if (savedByKey.has(key)) return send(res, 200, savedByKey.get(key))

  let raw = ''
  for await (const chunk of req) raw += chunk
  let input = {}
  try { input = JSON.parse(raw) } catch {}
  const description = String(input.description ?? '').trim()
  const category = String(input.category ?? '').trim()
  const date = String(input.date ?? '')
  const amount = Number(input.amount)
  if (!description || !category || !/^\d{4}-\d{2}-\d{2}$/.test(date) || !(amount > 0)) {
    return send(res, 400, { error: 'Description, amount, category and date are required' })
  }
  if (amount > 1_000_000) {
    return send(res, 422, { error: 'Amounts over 1,000,000 need a manager to approve them' })
  }
  const expense = { id: nextId++, description, amount: Math.round(amount * 100) / 100, category, date }
  expenses.unshift(expense)
  savedByKey.set(key, expense)
  send(res, 201, expense)
}).listen(3001, '127.0.0.1', () => console.log('API on http://localhost:3001'))
JS

A production API would keep the keys in its database with an expiry time, but the idea is the same. Start the API in your first terminal and leave it running:

Bash
node api/server.mjs

In your third terminal, send the same new expense twice with the same key, then list everything:

Bash
curl -s -X POST http://localhost:3001/api/expenses \
  -H 'Content-Type: application/json' -H 'Idempotency-Key: demo-lunch-1' \
  -d '{"description":"Lunch","amount":6.5,"category":"Food","date":"2026-11-10"}'
echo
curl -s -X POST http://localhost:3001/api/expenses \
  -H 'Content-Type: application/json' -H 'Idempotency-Key: demo-lunch-1' \
  -d '{"description":"Lunch","amount":6.5,"category":"Food","date":"2026-11-10"}'
echo
curl -s http://localhost:3001/api/expenses
echo

Check it worked

Both POST commands print the same expense, {"id":4,"description":"Lunch",...}, with the same id. The list has four expenses and "Lunch" appears once. The API terminal shows each request with key=demo-lunch-1 beside the two posts.

Step 2 · Send API calls through the dev server

The browser will load the app from the Angular dev server on port 4200. If the app called port 3001 directly, the browser would treat it as a different origin and block the response unless the API sent CORS headers. A proxy avoids that: the app calls /api/... on its own origin, and the dev server forwards the request to port 3001.

Create proxy.conf.json and make npm start use it:

Bash
cat > proxy.conf.json <<'JSON'
{
  "/api": {
    "target": "http://127.0.0.1:3001",
    "secure": false
  }
}
JSON
npm pkg set scripts.start="ng serve --proxy-config proxy.conf.json"

The proxy only exists in development. When you deploy, the web server that serves the built files (Nginx, Caddy or your host's rewrites) forwards /api in the same way.

Start the dev server in your second terminal and leave it running. The first build takes a few seconds:

Bash
npm start

In your third terminal, ask the dev server for the expenses:

Bash
curl -s http://localhost:4200/api/expenses
echo

Check it worked

The command prints the same four expenses as before, even though you asked port 4200. The API terminal logs a new GET /api/expenses.

Step 3 · Add routes for the list and the form

Give the app a shell with a heading and two links, and a <router-outlet /> where the current page appears. Replace the starter template and component:

Bash
cat > src/app/app.html <<'HTML'
<header>
  <h1>Expense tracker</h1>
  <nav>
    <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">All expenses</a>
    <a routerLink="/new" routerLinkActive="active">Add expense</a>
  </nav>
</header>
<main>
  <router-outlet />
</main>
HTML
cat > src/app/app.ts <<'TS'
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, RouterLink, RouterLinkActive],
  templateUrl: './app.html',
  styleUrl: './app.css',
})
export class App {}
TS
cat > src/styles.css <<'CSS'
body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 38rem; padding: 0 1rem; line-height: 1.5; }
nav { display: flex; gap: 1rem; margin-bottom: 1.5rem; }
nav a.active { font-weight: 700; text-decoration: none; }
form { display: grid; gap: 0.75rem; }
label { display: grid; gap: 0.2rem; }
input, select, button { font: inherit; padding: 0.4rem; }
.field-error, [role="alert"] { color: #a40000; margin: 0; }
.status { color: #555; }
CSS
rm src/app/app.spec.ts

The starter's app.spec.ts checked for the old "Hello" heading, so it goes; you add a test of your own later.

Now two page components. They are short for now and you fill them in over the next steps:

Bash
cat > src/app/expense-list.ts <<'TS'
import { Component } from '@angular/core';

@Component({
  selector: 'app-expense-list',
  template: `<h2>All expenses</h2>`,
})
export class ExpenseList {}
TS
cat > src/app/new-expense.ts <<'TS'
import { Component } from '@angular/core';

@Component({
  selector: 'app-new-expense',
  template: `<h2>New expense</h2>`,
})
export class NewExpense {}
TS

Map URLs to them in src/app/app.routes.ts:

Bash
cat > src/app/app.routes.ts <<'TS'
import { Routes } from '@angular/router';
import { ExpenseList } from './expense-list';

export const routes: Routes = [
  { path: '', title: 'Expenses', component: ExpenseList },
  {
    path: 'new',
    title: 'New expense',
    loadComponent: () => import('./new-expense').then((m) => m.NewExpense),
  },
  { path: '**', redirectTo: '' },
];
TS

Three things to notice. title sets the browser tab's text for each route. loadComponent puts the form in its own JavaScript file that the browser downloads only when someone opens /new, which keeps the first load smaller for people on slow or metered connections. The ** route sends any unknown URL back to the list.

Check it worked

Open http://localhost:4200/. The page shows "Expense tracker", the two links and "All expenses", and the tab reads "Expenses". Click Add expense: the heading changes to "New expense", the address ends in /new and the tab title changes too. In the Network panel of the developer tools you see a separate small .js file load the first time you open /new. Visiting http://localhost:4200/no-such-page lands you back on the list.

Step 4 · Load expenses with httpResource

Describe the data first, in src/app/expense.ts, so the rest of the app is typed against it:

Bash
cat > src/app/expense.ts <<'TS'
export interface Expense {
  id: number;
  description: string;
  amount: number;
  category: string;
  date: string; // YYYY-MM-DD
}
TS

httpResource uses HttpClient, so register it in src/app/app.config.ts:

Bash
cat > src/app/app.config.ts <<'TS'
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes), provideHttpClient()],
};
TS

Now the list. httpResource<Expense[]>(() => '/api/expenses') starts a GET when the component is created and gives you signals to read: value(), hasValue(), isLoading() and error(). If the URL function read other signals, a page number for example, the resource would fetch again whenever they changed. Replace src/app/expense-list.ts:

Bash
cat > src/app/expense-list.ts <<'TS'
import { Component, computed } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { httpResource } from '@angular/common/http';
import { Expense } from './expense';

@Component({
  selector: 'app-expense-list',
  imports: [DecimalPipe],
  template: `
    <h2>All expenses</h2>
    @if (expenses.hasValue()) {
      <ul>
        @for (expense of expenses.value(); track expense.id) {
          <li>
            {{ expense.date }} · {{ expense.description }} ({{ expense.category }}):
            {{ expense.amount | number: '1.2-2' }}
          </li>
        } @empty {
          <li>No expenses yet.</li>
        }
      </ul>
      <p><strong>Total: {{ total() | number: '1.2-2' }}</strong></p>
      <button type="button" (click)="expenses.reload()" [disabled]="expenses.isLoading()">
        {{ expenses.isLoading() ? 'Refreshing…' : 'Refresh' }}
      </button>
    } @else if (expenses.isLoading()) {
      <p class="status">Loading expenses…</p>
    } @else if (expenses.error()) {
      <p role="alert">
        Could not load expenses. Check your connection and try again.
        <button type="button" (click)="expenses.reload()">Try again</button>
      </p>
    }
  `,
})
export class ExpenseList {
  protected readonly expenses = httpResource<Expense[]>(() => '/api/expenses');

  protected readonly total = computed(() =>
    this.expenses.hasValue()
      ? this.expenses.value().reduce((sum, expense) => sum + expense.amount, 0)
      : 0,
  );
}
TS

The order of the @if branches matters. hasValue() comes first, so a refresh keeps the old list on screen and only the button changes to "Refreshing…". The loading message only shows when there is nothing to show yet. The error branch reads error() and offers reload(), which runs the same request again. Reading value() while the resource is in an error state throws, which is why the template and total check hasValue() before they touch it.

Check it worked

Reload http://localhost:4200/. "Loading expenses…" shows for half a second, then four expenses appear, newest first, with "Total: 62.20". Click Refresh: the list stays put while the button reads "Refreshing…". Now stop the API with Ctrl+C in its terminal and click Refresh again: the red message "Could not load expenses" appears with a Try again button. Start the API again with node api/server.mjs and click Try again: the list comes back. The API restarted with only its three starting expenses, so the total is now 55.70.

Step 5 · Add an interceptor that sets the Idempotency-Key header

Picture someone saving an expense on a phone with a weak signal. The request reaches the server and the expense is saved, but the response is lost, so the app reports a failure. They tap Save again. Without protection the list now has the expense twice. With an Idempotency-Key header, the second request carries the same key as the first, and the server answers with the expense it already saved.

The key has to belong to the form, not to the request: a fresh key per request would make every retry look new. So the form creates one key and attaches it to its request through an HttpContext token, and an interceptor turns that into the header. Create src/app/idempotency.interceptor.ts:

Bash
cat > src/app/idempotency.interceptor.ts <<'TS'
import { HttpContextToken, HttpInterceptorFn } from '@angular/common/http';

/** Set this on a request's context to send it with an Idempotency-Key header. */
export const IDEMPOTENCY_KEY = new HttpContextToken<string | null>(() => null);

export const idempotencyInterceptor: HttpInterceptorFn = (req, next) => {
  const key = req.context.get(IDEMPOTENCY_KEY);
  if (!key || req.headers.has('Idempotency-Key')) {
    return next(req);
  }
  return next(req.clone({ setHeaders: { 'Idempotency-Key': key } }));
};
TS

Requests are immutable, so the interceptor sends a modified clone. Requests without the token, such as the list's GET, pass through untouched. Register it with withInterceptors:

Bash
cat > src/app/app.config.ts <<'TS'
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideRouter } from '@angular/router';

import { idempotencyInterceptor } from './idempotency.interceptor';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    provideHttpClient(withInterceptors([idempotencyInterceptor])),
  ],
};
TS

Test it without a server. provideHttpClientTesting() swaps the network for HttpTestingController, which lets the test look at each outgoing request and answer it. Create src/app/idempotency.interceptor.spec.ts:

Bash
cat > src/app/idempotency.interceptor.spec.ts <<'TS'
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpContext, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IDEMPOTENCY_KEY, idempotencyInterceptor } from './idempotency.interceptor';

describe('idempotencyInterceptor', () => {
  let http: HttpClient;
  let backend: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideHttpClient(withInterceptors([idempotencyInterceptor])),
        provideHttpClientTesting(),
      ],
    });
    http = TestBed.inject(HttpClient);
    backend = TestBed.inject(HttpTestingController);
  });

  afterEach(() => backend.verify());

  it('adds the key from the request context as a header', () => {
    const context = new HttpContext().set(IDEMPOTENCY_KEY, 'key-123');
    http.post('/api/expenses', {}, { context }).subscribe();
    const request = backend.expectOne('/api/expenses');
    expect(request.request.headers.get('Idempotency-Key')).toBe('key-123');
    request.flush({});
  });

  it('leaves requests without a key alone', () => {
    http.get('/api/expenses').subscribe();
    const request = backend.expectOne('/api/expenses');
    expect(request.request.headers.has('Idempotency-Key')).toBe(false);
    request.flush([]);
  });
});
TS
npx ng test --watch=false

New Angular 22 projects run unit tests with Vitest in a simulated DOM (jsdom), so ng test needs no browser. --watch=false runs once and exits.

Check it worked

ng test builds the specs, then Vitest reports Test Files 1 passed (1) and Tests 2 passed (2). To see a failure, change 'key-123' in the toBe line to another value and run it again: Vitest prints the expected and received header values. Change it back afterwards.

Step 6 · Build a typed form with Signal Forms

Signal Forms (@angular/forms/signals) is stable in Angular 22. You keep the form's data in an ordinary signal(), and form() wraps it in a field tree with one field per property. Each field has its own signals, such as value(), errors(), touched() and invalid(), and the TypeScript types follow your model, so a typo in a field name is a compile error. The older reactive forms (FormGroup, FormControl) are still supported and fine to keep in existing apps; for a new form in a signal-based app, use Signal Forms.

Rules go in a schema function passed to form(). The submission option describes what happens on submit, and the formRoot directive on the <form> element wires it up: it stops the browser's own submit, marks the fields as touched so their errors show, and only runs action when every rule passes. Replace src/app/new-expense.ts:

Bash
cat > src/app/new-expense.ts <<'TS'
import { Component, inject, signal } from '@angular/core';
import { HttpClient, HttpContext, HttpErrorResponse } from '@angular/common/http';
import { FormField, FormRoot, form, maxLength, min, required } from '@angular/forms/signals';
import { Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';

import { Expense } from './expense';
import { IDEMPOTENCY_KEY } from './idempotency.interceptor';

interface ExpenseDraft {
  description: string;
  amount: number | null;
  category: string;
  date: string;
}

@Component({
  selector: 'app-new-expense',
  imports: [FormField, FormRoot],
  template: `
    <h2>New expense</h2>
    <form [formRoot]="expenseForm">
      <label>
        Description
        <input [formField]="expenseForm.description" />
      </label>
      @if (expenseForm.description().touched()) {
        @for (error of expenseForm.description().errors(); track error.kind) {
          <p class="field-error">{{ error.message }}</p>
        }
      }

      <label>
        Amount
        <input type="number" step="0.01" [formField]="expenseForm.amount" />
      </label>
      @if (expenseForm.amount().touched()) {
        @for (error of expenseForm.amount().errors(); track error.kind) {
          <p class="field-error">{{ error.message }}</p>
        }
      }

      <label>
        Category
        <select [formField]="expenseForm.category">
          <option value="Food">Food</option>
          <option value="Transport">Transport</option>
          <option value="Data and airtime">Data and airtime</option>
          <option value="Rent">Rent</option>
          <option value="Other">Other</option>
        </select>
      </label>

      <label>
        Date
        <input type="date" [formField]="expenseForm.date" />
      </label>
      @if (expenseForm.date().touched()) {
        @for (error of expenseForm.date().errors(); track error.kind) {
          <p class="field-error">{{ error.message }}</p>
        }
      }

      <button type="submit" [disabled]="expenseForm().submitting()">
        {{ expenseForm().submitting() ? 'Saving…' : 'Save expense' }}
      </button>
      @for (error of expenseForm().errors(); track error.kind) {
        <p role="alert">{{ error.message }}</p>
      }
    </form>
  `,
})
export class NewExpense {
  private readonly http = inject(HttpClient);
  private readonly router = inject(Router);
  private readonly idempotencyKey = crypto.randomUUID();

  protected readonly model = signal<ExpenseDraft>({
    description: '',
    amount: null,
    category: 'Food',
    date: new Date().toISOString().slice(0, 10),
  });

  protected readonly expenseForm = form(
    this.model,
    (expense) => {
      required(expense.description, { message: 'Say what the money was for' });
      maxLength(expense.description, 80, { message: 'Keep the description to 80 characters or fewer' });
      required(expense.amount, { message: 'Enter an amount' });
      min(expense.amount, 0.01, { message: 'The amount must be more than zero' });
      required(expense.date, { message: 'Pick a date' });
    },
    {
      submission: {
        action: async (field) => {
          try {
            await firstValueFrom(
              this.http.post<Expense>('/api/expenses', field().value(), {
                context: new HttpContext().set(IDEMPOTENCY_KEY, this.idempotencyKey),
              }),
            );
          } catch (err) {
            const message =
              err instanceof HttpErrorResponse && typeof err.error?.error === 'string'
                ? err.error.error
                : 'Could not save the expense. Check your connection and try again.';
            return { kind: 'server', message };
          }
          await this.router.navigateByUrl('/');
          return undefined;
        },
      },
    },
  );
}
TS

How the pieces fit:

  • [formField] binds an input to a field in both directions. For type="number" it writes a number into the model, and null when the box is empty, which is why amount is typed number | null. A date input bound to a string field gets the YYYY-MM-DD text the API expects.
  • Each rule takes a message, which ends up in that field's errors(). The template shows them only once the field is touched(), so nobody sees "Enter an amount" before they have had a chance to type one.
  • The action posts the model with the form's key in the request context, so the interceptor adds the header. idempotencyKey is created once per visit to the form, so pressing Save expense again after a failure reuses it.
  • If the server refuses, the action returns an error object instead of throwing. With no fieldTree named, it is attached to the whole form, and the template reads it from expenseForm().errors(). Returning undefined means success.
  • submitting() is true while the action runs, which disables the button and blocks double submits.

The browser's own checks (the required attribute and the Constraint Validation API) are not used here: formRoot turns them off with novalidate so the messages come from one place. Server-side checks still matter, which is why the API validates the body again.

Check it worked

Open Add expense and click Save expense with the form empty. "Say what the money was for" and "Enter an amount" appear in red and nothing is sent: the API terminal logs no POST. Type "Taxi to the airport", enter 2000000 as the amount and save. The server's message "Amounts over 1,000,000 need a manager to approve them" appears under the button. Change the amount to 18.75, pick Transport, set a date and save. The app returns to the list, the taxi fare is at the top and the total has gone up by 18.75. The API terminal shows both posts with the same key= value. In the Network panel, the POST request headers include Idempotency-Key.

Step 7 · Build for production

Stop the dev server with Ctrl+C in its terminal and build:

Bash
npm run build
ls dist/expenses-data/browser

The files in dist/expenses-data/browser are static: any web server can host them, as long as it forwards /api to your API and answers unknown paths such as /new with index.html so the router can handle them. Stop the API with Ctrl+C in its terminal. When you are done, delete the project:

Bash
cd ~
rm -rf ~/expenses-data

Check it worked

npm run build prints two tables, "Initial chunk files" and "Lazy chunk files", then "Application bundle generation complete". The form appears under the lazy chunks with the name new-expense, so it is not part of the first download. dist/expenses-data/browser contains index.html and the hashed .js and .css files.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.