Skip to main content

Web frameworks · Beginner · 25 min

Build your first Angular 22 app with standalone components and signals

By Padding · Updated 18 Nov 2026
node:26 image · Node.js 26.13 · Angular 22.3.0 · Angular CLI 22.3.0 · Vitest 5

You will create an Angular 22.3 project with the Angular CLI, build a small expense tracker from standalone components using signal, computed, input, output and the built-in @if and @for blocks, test it with ng test, then build it and serve the production files.

On this page

Angular is a TypeScript framework for building web apps from components. A component is a class with a decorator that gives it an HTML template and some CSS. Angular 22 apps are built from standalone components, which list what they use in their own imports array instead of belonging to a module, and they keep their state in signals: values that tell Angular exactly which parts of the page to update when they change.

In this tutorial you build an expense tracker. You start with one component that holds a list in a signal and works out a total from it. Then you split it into a row component and a form component that talk to their parent through input() and output(). You finish by testing it with ng test, building it with ng build, and serving the built files.

You need Node.js 26 from the Node.js install tutorial. The commands work the same on Linux and macOS.

Step 1 · Create the project

The Angular CLI creates, serves, tests and builds Angular projects. Run it with npx at a pinned version, so you get the same project as this tutorial even after newer releases come out:

Bash
cd ~
npx -y @angular/cli@22.3.0 new expense-tracker --defaults --style=css --routing=false --ssr=false --skip-git --ai-config=none
cd expense-tracker

The flags answer the questions ng new would otherwise ask. --defaults accepts the default for anything not given, --routing=false and --ssr=false leave out the router and server rendering (the next tutorial adds routes), --skip-git stops it creating a Git repository, and --ai-config=none skips the instruction files it can write for AI coding tools. Leave off --skip-git if you want the CLI to make the first commit for you. If the CLI asks whether to share usage data with the Angular team, either answer is fine.

Check it worked

The command lists the files it creates, then prints Packages installed successfully. Look at what you have:

Bash
ls src src/app
cat package.json

src/ holds index.html, main.ts, styles.css and app/. Inside app/ the root component is split across app.ts, app.html and app.css, with its test in app.spec.ts and app-wide settings in app.config.ts. Angular 22 names files without a .component suffix by default.

In package.json every @angular/ package is at ^22.3.0. Under devDependencies you find vitest and jsdom, which ng test uses, and typescript at ~6.0: Angular 22.3 supports TypeScript 6.0, not 7, so keep the version the CLI chose. There is no zone.js anywhere, which the next step explains.

Step 2 · Run the dev server and read the root component

Start the development server. It keeps running in this terminal, so open a second terminal in the same folder (cd ~/expense-tracker) for the rest of the tutorial:

Bash
npm start

npm start runs ng serve, which compiles the app, prints Local: http://localhost:4200/ and watches for changes. Open that address and you see the CLI's welcome page with Hello, expense-tracker. From the second terminal, look at the page and the files that start the app:

Bash
curl -s http://localhost:4200/ | grep -o '<app-root></app-root>'
cat src/main.ts src/app/app.config.ts src/app/app.ts

Check it worked

curl prints <app-root></app-root>, the empty element Angular fills in. Then read the three files:

  • main.ts calls bootstrapApplication(App, appConfig). That starts the app from one component, with no NgModule in sight.
  • app.config.ts lists app-wide providers. There is no zone setting because zoneless is the default for new apps. Older Angular apps loaded a library called zone.js that patched every browser event and timer so Angular knew when to check the page. A new Angular 22 app does not: Angular updates the page when a signal it reads changes, or when an event bound in a template fires.
  • app.ts holds the App class. @Component gives it a selector (the app-root tag in index.html), a templateUrl and a styleUrl, plus an imports array for the other components its template uses. Components are standalone by default, so you never write standalone: true. The class already has one signal: title = signal('expense-tracker').

Angular 22 also makes OnPush the default change detection strategy, so a component is only checked when its inputs change, an event fires in it, or a signal it reads changes. Signals fit that model, which is why you use them for all state in this tutorial.

If you work on a remote server, the dev server only listens on localhost. Forward port 4200 over SSH, or run npm start -- --host 0.0.0.0 on a trusted network only, because the dev server is not meant to face the internet.

Step 3 · Hold state in a signal and derive the total with computed

Create a type for an expense and a small function that formats amounts, then replace the root component with a version that keeps a list of expenses:

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

const currency = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' });

export function formatAmount(amount: number): string {
  return currency.format(amount);
}
TS
cat > src/app/app.ts <<'TS'
import { Component, computed, signal } from '@angular/core';
import { Expense, formatAmount } from './expense';

@Component({
  selector: 'app-root',
  imports: [],
  templateUrl: './app.html',
  styleUrl: './app.css',
})
export class App {
  protected readonly expenses = signal<Expense[]>([
    { id: 1, description: 'Bus fare', amount: 800 },
    { id: 2, description: 'Data bundle', amount: 1500 },
  ]);
  protected readonly total = computed(() =>
    this.expenses().reduce((sum, expense) => sum + expense.amount, 0),
  );
  protected readonly format = formatAmount;

  protected removeExpense(id: number) {
    this.expenses.update((list) => list.filter((expense) => expense.id !== id));
  }
}
TS
cat > src/app/app.html <<'HTML'
<main>
  <h1>Expenses</h1>
  <p class="summary">{{ expenses().length }} {{ expenses().length === 1 ? 'expense' : 'expenses' }}, total {{ format(total()) }}</p>

  @if (expenses().length > 0) {
    <ul>
      @for (expense of expenses(); track expense.id) {
        <li>
          <span class="description">{{ expense.description }}</span>
          <span class="amount">{{ format(expense.amount) }}</span>
          <button type="button" [attr.aria-label]="'Remove ' + expense.description" (click)="removeExpense(expense.id)">
            Remove
          </button>
        </li>
      }
    </ul>
  } @else {
    <p class="empty">No expenses yet. Add one below.</p>
  }
</main>
HTML
cat > src/app/app.css <<'CSS'
main {
  max-width: 32rem;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: system-ui, sans-serif;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  display: flex;
  gap: 0.75rem;
  align-items: center;
  padding: 0.4rem 0;
}

.description {
  flex: 1;
}

.amount {
  font-variant-numeric: tabular-nums;
}
CSS

How the pieces work:

  • signal<Expense[]>([...]) creates a writable signal holding the list. You read a signal by calling it, expenses(), in the class and in the template alike. You change it with set(newValue) or with update(fn), which hands you the current value and stores what you return.
  • removeExpense builds a new array with filter instead of changing the old one. Signals compare values by identity, so a new array is what tells Angular the list changed. Pushing into the existing array would leave the page stale.
  • computed derives a read-only signal from others. total re-runs only when expenses changes, and caches its result between reads. Work things out with computed instead of storing a second copy that can drift.
  • @if (...) { } @else { } adds or removes a block of the page. When the list is empty the <ul> is gone from the page entirely, and the message takes its place.
  • @for (expense of expenses(); track expense.id) repeats the <li> for each expense. track is required: it gives each row an identity, so when one expense is removed Angular deletes that row instead of redrawing the list. Use an ID from your data. @for also takes an @empty { } block for an empty list, which is handy when you have no wrapping element to remove.
  • (click)="..." binds an event, and [attr.aria-label]="..." binds an attribute to an expression. The label gives each button a distinct name for screen readers.
  • {{ }} can hold a short expression. The summary uses expenses().length === 1 ? 'expense' : 'expenses' so one item reads 1 expense, not 1 expenses.
  • {{ }} always prints text, never HTML, so a description such as <b>Hi</b> shows the angle brackets. That protects you from injected markup.

The amounts use Intl.NumberFormat with the en-NG locale and Nigerian naira. Swap in your own pair, such as en-KE with KES or en-GH with GHS, and the browser formats the amount the way people there expect.

Check it worked

The browser reloads when you save. You see two expenses and 2 expenses, total ₦2,300.00. Click Remove on Bus fare and the summary becomes 1 expense, total ₦1,500.00 with no reload. Remove the other one and No expenses yet. Add one below. replaces the list. Reload the page to get the starter list back.

If the page stays blank, the terminal running npm start shows the compiler error with a file name and line.

Step 4 · Split the app into components with input and output

Move each row into an ExpenseItem component and add an ExpenseForm component for new expenses. Data goes down to a child through an input, and the child reports back to its parent through an output. The parent stays the only place that changes the list:

Bash
mkdir -p src/app/expense-item src/app/expense-form
cat > src/app/expense-item/expense-item.ts <<'TS'
import { Component, input, output } from '@angular/core';
import { Expense, formatAmount } from '../expense';

@Component({
  selector: 'app-expense-item',
  template: `
    <span class="description">{{ expense().description }}</span>
    <span class="amount">{{ format(expense().amount) }}</span>
    <button type="button" [attr.aria-label]="'Remove ' + expense().description" (click)="remove.emit(expense().id)">
      Remove
    </button>
  `,
  styles: `
    :host {
      display: flex;
      gap: 0.75rem;
      align-items: center;
      padding: 0.4rem 0;
    }
    .description {
      flex: 1;
    }
    .amount {
      font-variant-numeric: tabular-nums;
    }
  `,
})
export class ExpenseItem {
  readonly expense = input.required<Expense>();
  readonly remove = output<number>();
  protected readonly format = formatAmount;
}
TS
cat > src/app/expense-form/expense-form.ts <<'TS'
import { Component, computed, output, signal } from '@angular/core';

export interface NewExpense {
  description: string;
  amount: number;
}

@Component({
  selector: 'app-expense-form',
  template: `
    <form (submit)="submit($event)">
      <label>
        Description
        <input #descriptionBox [value]="description()" (input)="description.set(descriptionBox.value)" />
      </label>
      <label>
        Amount
        <input #amountBox type="number" min="0" step="0.01" inputmode="decimal"
               [value]="amountText()" (input)="amountText.set(amountBox.value)" />
      </label>
      <button type="submit" [disabled]="!canAdd()">Add expense</button>
    </form>
  `,
  styles: `
    form {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
      align-items: end;
      margin-top: 1rem;
    }
    label {
      display: grid;
      gap: 0.25rem;
    }
  `,
})
export class ExpenseForm {
  readonly added = output<NewExpense>();

  protected readonly description = signal('');
  protected readonly amountText = signal('');
  protected readonly amount = computed(() => Number(this.amountText()));
  protected readonly canAdd = computed(
    () => this.description().trim() !== '' && this.amountText() !== '' && this.amount() > 0,
  );

  protected submit(event: Event) {
    event.preventDefault();
    if (!this.canAdd()) return;
    this.added.emit({ description: this.description().trim(), amount: this.amount() });
    this.description.set('');
    this.amountText.set('');
  }
}
TS
cat > src/app/app.ts <<'TS'
import { Component, computed, signal } from '@angular/core';
import { Expense, formatAmount } from './expense';
import { ExpenseForm, NewExpense } from './expense-form/expense-form';
import { ExpenseItem } from './expense-item/expense-item';

@Component({
  selector: 'app-root',
  imports: [ExpenseItem, ExpenseForm],
  templateUrl: './app.html',
  styleUrl: './app.css',
})
export class App {
  protected readonly expenses = signal<Expense[]>([
    { id: 1, description: 'Bus fare', amount: 800 },
    { id: 2, description: 'Data bundle', amount: 1500 },
  ]);
  protected readonly total = computed(() =>
    this.expenses().reduce((sum, expense) => sum + expense.amount, 0),
  );
  protected readonly format = formatAmount;
  private nextId = 3;

  protected addExpense(entry: NewExpense) {
    const expense: Expense = { id: this.nextId++, ...entry };
    this.expenses.update((list) => [...list, expense]);
  }

  protected removeExpense(id: number) {
    this.expenses.update((list) => list.filter((expense) => expense.id !== id));
  }
}
TS
cat > src/app/app.html <<'HTML'
<main>
  <h1>Expenses</h1>
  <p class="summary">{{ expenses().length }} {{ expenses().length === 1 ? 'expense' : 'expenses' }}, total {{ format(total()) }}</p>

  @if (expenses().length > 0) {
    <ul>
      @for (expense of expenses(); track expense.id) {
        <li>
          <app-expense-item [expense]="expense" (remove)="removeExpense($event)" />
        </li>
      }
    </ul>
  } @else {
    <p class="empty">No expenses yet. Add one below.</p>
  }

  <app-expense-form (added)="addExpense($event)" />
</main>
HTML
cat > src/app/app.css <<'CSS'
main {
  max-width: 32rem;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: system-ui, sans-serif;
}

ul {
  list-style: none;
  padding: 0;
}
CSS

The new pieces:

  • input.required<Expense>() declares an input the parent must pass. It is a read-only signal, so the template reads it as expense(). The parent passes it with square brackets, [expense]="expense", and the compiler reports an error if a parent leaves it out or passes the wrong type. Use input<T>(defaultValue) for an optional one.
  • output<number>() declares an event. The child calls remove.emit(id), and the parent listens with (remove)="removeExpense($event)", where $event is the value that was emitted.
  • ExpenseItem has its template and styles inline in the decorator. That suits small components. Its styles are scoped to the component, and :host targets the <app-expense-item> element itself.
  • ExpenseForm keeps the half-typed text in its own signals, because nothing else needs it, and only tells the parent about a finished expense. #descriptionBox is a template reference variable: a name for the input element, so (input) can copy its value into the signal on each keystroke. canAdd is a computed that disables the button until there is a description and an amount above zero.
  • App lists both children in imports. Leave one out and the build fails with an error that the element is unknown, which is how standalone components keep dependencies visible.

inputmode="decimal" brings up a number keypad with a decimal point on phones. For readers on low-end Android handsets, a short form with the right keyboard saves taps and mistakes.

Check it worked

The list looks the same as before, with a form underneath. Add expense is greyed out until you fill in both boxes. Add Lunch for 1200 and it appears at the bottom, the total becomes ₦3,500.00 and the boxes clear. Descriptions in any script, such as Yoruba with tone marks (Ọjà market) or Amharic in Ge'ez script, show exactly as typed. Remove everything and the empty message appears.

Step 5 · Test the components with ng test

New Angular 22 projects run unit tests with Vitest, in Node.js with jsdom standing in for the browser. Replace the generated test with tests for what the app does:

Bash
cat > src/app/app.spec.ts <<'TS'
import { TestBed } from '@angular/core/testing';
import { App } from './app';

describe('App', () => {
  async function render() {
    await TestBed.configureTestingModule({ imports: [App] }).compileComponents();
    const fixture = TestBed.createComponent(App);
    await fixture.whenStable();
    return { fixture, page: fixture.nativeElement as HTMLElement };
  }

  function typeInto(page: HTMLElement, index: number, value: string) {
    const box = page.querySelectorAll('input')[index];
    box.value = value;
    box.dispatchEvent(new Event('input'));
  }

  it('shows the starter expenses and their total', async () => {
    const { page } = await render();
    expect(page.querySelectorAll('li').length).toBe(2);
    expect(page.querySelector('.summary')?.textContent).toContain('2 expenses, total ₦2,300.00');
  });

  it('adds an expense and updates the total', async () => {
    const { fixture, page } = await render();
    typeInto(page, 0, 'Lunch');
    typeInto(page, 1, '1200');
    await fixture.whenStable();
    page.querySelector<HTMLButtonElement>('button[type="submit"]')?.click();
    await fixture.whenStable();
    expect(page.querySelectorAll('li').length).toBe(3);
    expect(page.querySelector('.summary')?.textContent).toContain('total ₦3,500.00');
  });

  it('uses the singular for one expense and shows the empty message when none are left', async () => {
    const { fixture, page } = await render();
    const buttons = Array.from(page.querySelectorAll<HTMLButtonElement>('li button'));
    buttons[0].click();
    await fixture.whenStable();
    expect(page.querySelector('.summary')?.textContent).toContain('1 expense, total ₦1,500.00');
    buttons[1].click();
    await fixture.whenStable();
    expect(page.querySelector('ul')).toBeNull();
    expect(page.querySelector('.empty')?.textContent).toContain('No expenses yet');
  });
});
TS
npx ng test --watch=false

TestBed creates the component the way the app would. Because the app is zoneless, nothing updates on its own schedule in a test: after typing or clicking, await fixture.whenStable() waits for Angular to apply the signal changes to the page before you check it. Without --watch=false, ng test keeps running and re-runs the tests each time you save a file.

Check it worked

Vitest prints Test Files 1 passed (1) and Tests 3 passed (3). To see a failure, change toBe(3) to toBe(4) in the second test and run it again: Vitest names the test and shows the expected and received values. Change it back afterwards.

Step 6 · Build for production and serve the result

Stop the dev server with Ctrl+C in the first terminal.

Build the app. ng build compiles the templates ahead of time, bundles and minifies the code, and writes the result to dist/expense-tracker/browser/:

Bash
npm run build
ls dist/expense-tracker/browser

The output lists the initial files with their raw and estimated transfer sizes, then Application bundle generation complete. The folder holds index.html, favicon.ico, and main- and styles- files with a hash in each name. The estimated transfer size is something like 35 kB, Angular included. Smaller bundles load faster on prepaid mobile data, which is how many readers across Africa reach the web.

Serve the folder with a small static file server to check it. Like the dev server, it keeps running in the terminal:

Bash
npx -y http-server@14.1.1 dist/expense-tracker/browser -p 8080
Bash
curl -s http://localhost:8080/ | grep -o '<script src="main-[^"]*"'

Check it worked

curl prints a <script> tag pointing at a hashed main- file, not at src/main.ts, which shows you are looking at the built app. Open http://localhost:8080/ in a browser and repeat the checks: add an expense, remove them all.

Stop the server with Ctrl+C.

The contents of dist/expense-tracker/browser/ are plain HTML, CSS and JavaScript. To publish the app, upload that folder to any static host or serve it with a web server such as Nginx. The server needs no Node.js.

Step 7 · Tidy up

The expenses live in memory, so they reset when you reload the page. The next tutorial loads them from an API and replaces the hand-built form with Angular's forms, but it rebuilds the expense tracker in a fresh project so your files match that page. You do not need to keep this one. Remove it, or keep it for reference:

Bash
cd ~
rm -rf ~/expense-tracker

Check it worked

ls ~ no longer lists expense-tracker.

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.