Contents

Angular Cheat Sheet

In this Angular cheat sheet, you'll find every decorator, block, operator and CLI flag worth remembering. Searchable, filterable, copy-ready.

By Bogdan SanduUpdated July 29, 2026

Checked against the Angular 22 release and the official release notes

CLI & Setup

Scaffold, serve, build and migrate. Every flag you actually type.

Create a workspace

setup

New application

Angular 22 generates standalone, zoneless, OnPush projects by default.

ng new my-app

Skip prompts, accept defaults

ng new my-app --defaults

Pick a stylesheet format

Options: css, scss, sass, less.

ng new my-app --style=scss

With server-side rendering

v20+

Adds @angular/ssr, a server entry point and hydration wiring.

ng new my-app --ssr

Without SSR

ng new my-app --no-ssr

Keep Zone.js instead of zoneless

v20+

New v22 projects are zoneless unless you opt out.

ng new my-app --no-zoneless

NgModule based project

legacy

Only for teams still on the module architecture.

ng new my-app --no-standalone

Choose a package manager

Also accepts npm, yarn, bun, cnpm.

ng new my-app --package-manager=pnpm

Set the selector prefix

Components become <acme-user-card>.

ng new my-app --prefix=acme

Create without installing deps

ng new my-app --skip-install

Empty workspace, no app

Useful for a monorepo of libraries.

ng new my-workspace --create-application=false

Serve, build, watch

Dev server

Alias: ng s. Hot module replacement is on by default.

ng serve

Custom port and auto-open

ng serve --port 4300 --open

Expose on the local network

Handy for testing on a phone.

ng serve --host 0.0.0.0

Serve a named configuration

ng serve --configuration=production

Disable hot module replacement

ng serve --no-hmr

Production build

Defaults to the production configuration.

ng build

Development build

ng build --configuration development

Rebuild on change

ng build --watch

Emit a bundle stats file

Feed it to a bundle analyzer.

ng build --stats-json

Deploy under a sub-path

ng build --base-href /app/

Control file hashing

Values: none, media, bundles, all.

ng build --output-hashing=all

Source maps in a prod build

ng build --source-map

Generate code

schematics

Component

Short form: ng g c user-card.

ng generate component user-card

Component in a folder, flat

ng g c shared/user-card --flat

Inline template and styles

ng g c badge --inline-template --inline-style

Component without a spec file

ng g c badge --skip-tests

Service

Short form: ng g s data.

ng g service data

Attribute directive

ng g directive highlight

Pipe

ng g pipe truncate

Functional route guard

ng g guard auth --functional

HTTP interceptor

ng g interceptor auth

Route resolver

ng g resolver user

Interface, enum, class

ng g interface user
ng g enum status
ng g class user-model

Environment files

Creates src/environments and wires the file replacement.

ng g environments

Extra app or library in the workspace

ng g application admin
ng g library ui-kit

NgModule with routing

legacy

ng g module admin --routing

Update, add, inspect

maintenance

Show what can be updated

ng update

Update the framework and CLI together

Core and CLI majors must match.

ng update @angular/core @angular/cli

Jump to a specific major

ng update @angular/core@22 @angular/cli@22

Add a package with its schematic

Runs the library's install-time setup.

ng add @angular/material

Add SSR to an existing app

v20+

ng add @angular/ssr

Turn the app into a PWA

ng add @angular/pwa

Print versions and environment

Short form: ng v.

ng version

Run unit tests once, headless

Vitest is the default runner in v22.

ng test --watch=false --browsers=ChromeHeadless

Tests with coverage

ng test --coverage

Lint

Requires ng add @angular/eslint first.

ng lint

Manage the build cache

ng cache info
ng cache clean
ng cache disable

Opt out of usage analytics

ng analytics off

Read or set a workspace config value

ng config cli.packageManager pnpm

Automated migrations

codemods

Convert to standalone components

v19+

Run it three times: convert, prune imports, bootstrap.

ng generate @angular/core:standalone

Rewrite *ngIf and *ngFor as @if and @for

v19+

ng generate @angular/core:control-flow

Convert @Input() to signal input()

v19+

ng generate @angular/core:signal-inputs

Convert @Output() to output()

v19+

ng generate @angular/core:output-migration

Convert @ViewChild and @ContentChild to signal queries

v19+

ng generate @angular/core:signal-queries

Move constructor params to inject()

v19+

ng generate @angular/core:inject

Drop unused standalone imports

v19+

ng generate @angular/core:cleanup-unused-imports

Use self-closing tags

v19+

ng generate @angular/core:self-closing-tag

Components

The unit of everything: metadata, inputs, outputs, lifecycle, queries, projection.

Anatomy

Minimal standalone component

standalone: true is the default since v19, so you no longer write it.

import { Component } from '@angular/core';

@Component({
  selector: 'app-hello',
  template: `<h1>Hello</h1>`,
})
export class Hello {}

External template and styles

styleUrl is singular; use styleUrls only for an array of files.

@Component({
  selector: 'app-user',
  templateUrl: './user.html',
  styleUrl: './user.css',
})
export class User {}

Import what the template uses

Standalone components declare their own template dependencies.

@Component({
  selector: 'app-page',
  imports: [UserCard, DatePipe, RouterLink],
  template: `<app-user-card />`,
})
export class Page {}

Change detection strategy

v20+

OnPush is the default for new components in v22, so this line is usually redundant.

@Component({
  selector: 'app-row',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `...`,
})
export class Row {}

Style encapsulation

@Component({
  encapsulation: ViewEncapsulation.None,
  // Emulated (default) | None | ShadowDom
})
export class Theme {}

Host element bindings in metadata

Preferred over @HostBinding and @HostListener in modern style guides.

@Component({
  selector: 'app-chip',
  host: {
    'class': 'chip',
    '[class.is-active]': 'active()',
    '[attr.role]': '"button"',
    '(click)': 'toggle()',
  },
})
export class Chip {}

Selectorless usage

experimental

Experimental in v22: reference the class directly instead of a string selector.

import { UserCard } from './user-card';

@Component({
  imports: [UserCard],
  template: `<UserCard [user]="user()" />`,
})
export class Page {}

Bootstrap the application

import { bootstrapApplication } from '@angular/platform-browser';

bootstrapApplication(App, {
  providers: [provideRouter(routes), provideHttpClient()],
});

Signal inputs and outputs

recommended

Optional input with a default

v17+

Reads as a signal: this.size().

size = input('medium');
// template: <app-chip size="large" />

Required input

v17+

The compiler errors if a parent forgets to bind it.

user = input.required<User>();

Aliased input

v17+

value = input(0, { alias: 'count' });

Transform an incoming value

v17+

booleanAttribute makes <app-x disabled> resolve to true.

import { booleanAttribute, numberAttribute } from '@angular/core';

disabled = input(false, { transform: booleanAttribute });
age = input(0, { transform: numberAttribute });

Custom transform

v17+

name = input('', { transform: (v: string) => v.trim().toLowerCase() });

Output and emit

v17+

saved = output<User>();

save() {
  this.saved.emit(this.user());
}
// template: <app-form (saved)="onSaved($event)" />

Output with no payload

v17+

closed = output();
this.closed.emit();

Two-way binding with model()

v17+

model() is a writable signal that also emits checkedChange.

checked = model(false);

toggle() {
  this.checked.update(v => !v);
}
// parent: <app-toggle [(checked)]="isOn" />

Required model

v17+

value = model.required<string>();

Output from an observable

v16+

import { outputFromObservable } from '@angular/core/rxjs-interop';

search = outputFromObservable(this.query$);

Decorator inputs and outputs

legacy

Basic input

legacy

Still supported, but signal inputs are the recommended path.

@Input() user!: User;

Required and aliased input

legacy

@Input({ required: true, alias: 'userId' }) id!: string;

Input with transform

legacy

@Input({ transform: booleanAttribute }) disabled = false;

Setter input

legacy

@Input()
set user(value: User) {
  this._user = value;
}

Output with EventEmitter

legacy

@Output() saved = new EventEmitter<User>();
this.saved.emit(user);

Manual two-way binding

legacy

The Change suffix is what makes the banana-in-a-box syntax work.

@Input() value = '';
@Output() valueChange = new EventEmitter<string>();
// parent: <app-x [(value)]="text" />

React to input changes

legacy

With signal inputs, use computed() or effect() instead.

ngOnChanges(changes: SimpleChanges) {
  if (changes['user'] && !changes['user'].firstChange) {
    this.reload();
  }
}

Lifecycle hooks

order matters

Initialize after first inputs are set

Runs once, after the first ngOnChanges.

ngOnInit() {
  this.load();
}

Respond to input changes

Runs before ngOnInit and on every input update.

ngOnChanges(changes: SimpleChanges) { }

Custom change detection

Runs very often. Keep it cheap or avoid it.

ngDoCheck() { }

Projected content is ready

ngAfterContentInit() { }
ngAfterContentChecked() { }

View and child views are ready

Safe place to touch DOM from @ViewChild.

ngAfterViewInit() { }
ngAfterViewChecked() { }

Clean up

ngOnDestroy() {
  this.sub.unsubscribe();
}

Clean up without implementing the interface

v16+

private destroyRef = inject(DestroyRef);

constructor() {
  this.destroyRef.onDestroy(() => clearInterval(this.id));
}

Run once after the next render

v16+

Browser only, so it is safe for DOM measurement under SSR.

import { afterNextRender } from '@angular/core';

constructor() {
  afterNextRender(() => {
    this.chart = new Chart(this.el.nativeElement);
  });
}

Run after every render

v20+

Named afterRender before v20.

import { afterEveryRender } from '@angular/core';

afterEveryRender(() => this.syncScroll());

Reactive render effect

v20+

import { afterRenderEffect } from '@angular/core';

afterRenderEffect(() => {
  this.el.nativeElement.style.height = this.height() + 'px';
});

View and content queries

references

Single view child

v17+

input = viewChild<ElementRef>('box');
// this.input()?.nativeElement

Required view child

v17+

No optional chaining needed at the call site.

canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas');

Many view children

v17+

rows = viewChildren(RowComponent);
// this.rows() is a readonly array

Query a component instance

v17+

picker = viewChild(DatePicker);

Read a specific token

v17+

vcr = viewChild('host', { read: ViewContainerRef });

Projected content queries

v17+

tabs = contentChildren(Tab);
header = contentChild(TabHeader);

Decorator view child

legacy

static: true resolves before ngOnInit but only for non-conditional elements.

@ViewChild('box') box!: ElementRef;
@ViewChild('box', { static: true }) early!: ElementRef;

Decorator content children

legacy

@ContentChildren(Tab, { descendants: true }) tabs!: QueryList<Tab>;

Content projection

composition

Single slot

<div class="card">
  <ng-content />
</div>

Named slots

Unmatched content falls into the bare <ng-content />.

<header><ng-content select="[card-title]" /></header>
<div><ng-content /></div>
<footer><ng-content select="card-actions" /></footer>

Consume the slots

<app-card>
  <h2 card-title>Billing</h2>
  <p>Body copy.</p>
  <card-actions><button>Save</button></card-actions>
</app-card>

Fallback content when nothing is projected

v20+

Supported from v18.

<ng-content select="[icon]">
  <svg class="default-icon">...</svg>
</ng-content>

Project under a different selector

<app-card>
  <div ngProjectAs="card-actions">
    <button>Delete</button>
  </div>
</app-card>

Host bindings and directive composition

host

Bind a host property

legacy

@HostBinding('class.active') isActive = false;
@HostBinding('attr.aria-expanded') expanded = 'false';

Listen on the host

legacy

@HostListener('click', ['$event'])
onClick(e: MouseEvent) { }

Listen on window or document

legacy

@HostListener('window:resize')
onResize() { }

Compose behaviour from directives

Applies directives to the host without touching the template.

@Component({
  selector: 'app-menu',
  hostDirectives: [
    CdkTrapFocus,
    { directive: Tooltip, inputs: ['text: tip'], outputs: ['shown'] },
  ],
})
export class Menu {}

Templates & Binding

Everything you can write between the angle brackets.

Interpolation and property binding

data in

Interpolation

<h1>{{ title() }}</h1>
<p>{{ 'Total: ' + count() }}</p>

Property binding

<img [src]="avatarUrl()" [alt]="user().name" />

Static attribute vs bound property

<input value="static" [value]="dynamic()" />

Attribute binding

Use attr. when there is no matching DOM property, like colspan or aria-*.

<td [attr.colspan]="span()" [attr.aria-label]="label()"></td>

Remove an attribute

null removes the attribute entirely.

<button [attr.disabled]="isDisabled() ? '' : null">Save</button>

Single class toggle

<div [class.is-open]="open()"></div>

Class object or string

<div [class]="{ active: isActive(), lg: isLarge() }"></div>
<div [class]="'a b c'"></div>

Style with a unit

<div [style.width.px]="width()" [style.font-size.rem]="size()"></div>

Style object

<div [style]="{ color: fg(), background: bg() }"></div>

Bind a custom property

<div [style.--brand]="brandColor()"></div>

Event binding

data out

Basic listener

<button (click)="save()">Save</button>

The event object

v17+

<input (input)="onInput($event)" />
// onInput(e: Event) { (e.target as HTMLInputElement).value }

Key modifiers

<input (keydown.enter)="submit()" (keydown.escape)="cancel()" />

Key combinations

v17+

<div (keydown.control.s)="save($event)"></div>
<div (keydown.meta.shift.k)="palette()"></div>

Template reference as argument

<input #box />
<button (click)="send(box.value)">Send</button>

Custom component output

v17+

<app-form (saved)="onSaved($event)" (cancelled)="close()" />

Statement chaining

<button (click)="first(); second()">Both</button>

Two-way binding and refs

sync

Two-way with ngModel

Requires FormsModule in imports.

<input [(ngModel)]="name" />

Two-way with a model input

v17+

Works with model() on the child.

<app-toggle [(checked)]="isOn" />

Expanded two-way form

v17+

<app-toggle [checked]="isOn" (checkedChange)="isOn = $event" />

Template reference variable

<video #player></video>
<button (click)="player.play()">Play</button>

Reference a directive instance

The name comes from the directive's exportAs.

<form #f="ngForm">...</form>
<button [disabled]="f.invalid">Send</button>

Local template variable

v18+

@let is read-only in the template and available from v18.

@let fullName = user().first + ' ' + user().last;
<p>{{ fullName }}</p>

@let with an async value

v18+

@let profile = profile$ | async;
@if (profile) {
  <h2>{{ profile.name }}</h2>
}

Expression helpers

syntax

Safe navigation

<p>{{ user()?.address?.city }}</p>

Non-null assertion

Silences the strict template check only; it does not guard at runtime.

<p>{{ user()!.name }}</p>

Nullish coalescing

<p>{{ nickname() ?? 'Anonymous' }}</p>

Ternary

<span>{{ count() > 0 ? 'Items' : 'Empty' }}</span>

Escape hatch for types

<p>{{ $any(user()).legacyField }}</p>

Grouping element with no DOM output

ng-container renders nothing itself.

<ng-container [ngTemplateOutlet]="tpl" />

Self-closing component tag

Supported from v16.

<app-user-card />

Void and pipe together

<p>{{ amount() | currency:'EUR':'symbol':'1.2-2' }}</p>

Templates as values

Declare and render a template

<ng-template #empty>
  <p>Nothing here yet.</p>
</ng-template>

<ng-container *ngTemplateOutlet="empty" />

Pass context to a template

$implicit fills the let-item slot.

<ng-template #row let-item let-i="index">
  <li>{{ i }}: {{ item.name }}</li>
</ng-template>

<ng-container
  [ngTemplateOutlet]="row"
  [ngTemplateOutletContext]="{ $implicit: user, index: 0 }" />

Accept a template as an input

itemTemplate = input<TemplateRef<{ $implicit: Item }>>();

Render a component dynamically

<ng-container
  [ngComponentOutlet]="widget()"
  [ngComponentOutletInputs]="{ title: 'Sales' }" />

Create a view imperatively

private vcr = inject(ViewContainerRef);

show(tpl: TemplateRef<unknown>) {
  this.vcr.clear();
  this.vcr.createEmbeddedView(tpl);
}

Create a component imperatively

const ref = this.vcr.createComponent(ToastComponent);
ref.setInput('message', 'Saved');
ref.destroy();

Control Flow

Built-in blocks, deferred loading, and the structural directives they replaced.

Conditionals and loops

v17+

@if

v17+

@if (user()) {
  <p>Welcome back.</p>
}

@if / @else if / @else

v17+

@if (status() === 'loading') {
  <app-spinner />
} @else if (status() === 'error') {
  <app-error />
} @else {
  <app-content />
}

Alias the condition result

v17+

Avoids calling the signal repeatedly.

@if (user(); as u) {
  <p>{{ u.name }}</p>
}

@for with a track expression

v17+

track is mandatory. Use a stable unique key, not $index, whenever you have one.

@for (item of items(); track item.id) {
  <li>{{ item.name }}</li>
}

@for with @empty

v17+

@for (todo of todos(); track todo.id) {
  <li>{{ todo.title }}</li>
} @empty {
  <li class="muted">Nothing to do.</li>
}

Loop context variables

v17+

Available: $index, $first, $last, $even, $odd, $count.

@for (row of rows(); track row.id; let i = $index, isFirst = $first) {
  <tr [class.first]="isFirst">{{ i }} - {{ row.label }}</tr>
}

Track by index for primitives

v17+

@for (tag of tags(); track $index) {
  <span>{{ tag }}</span>
}

@switch

v17+

Comparison is strict equality, and @default is optional.

@switch (role()) {
  @case ('admin') { <app-admin /> }
  @case ('editor') { <app-editor /> }
  @default { <app-viewer /> }
}

Deferred loading

@defer

Lazy load a chunk of template

v17+

Defaults to the on idle trigger.

@defer {
  <app-heavy-chart />
}

Full block with all sub-blocks

v17+

after delays showing the loader; minimum prevents a flash.

@defer (on viewport) {
  <app-comments />
} @placeholder (minimum 500ms) {
  <div class="skeleton"></div>
} @loading (after 100ms; minimum 1s) {
  <app-spinner />
} @error {
  <p>Could not load comments.</p>
}

Trigger on interaction or hover

v17+

@defer (on interaction) { <app-editor /> }
@defer (on hover) { <app-preview /> }

Trigger from another element

v17+

<button #more>Show more</button>

@defer (on interaction(more)) {
  <app-details />
}

Timer and immediate triggers

v17+

@defer (on timer(2s)) { <app-promo /> }
@defer (on immediate) { <app-banner /> }

Condition based trigger

v17+

when evaluates once and does not re-trigger after it fires.

@defer (when isVisible()) {
  <app-panel />
}

Combine triggers

v17+

Whichever fires first wins.

@defer (on viewport; on timer(5s)) {
  <app-widget />
}

Prefetch ahead of time

v17+

@defer (on interaction; prefetch on idle) {
  <app-editor />
}

Incremental hydration

v19+

Server renders the content, and the client only hydrates it when the trigger fires.

@defer (hydrate on viewport) {
  <app-product-grid />
}

Never hydrate static content

v19+

@defer (hydrate never) {
  <app-legal-footer />
}

Structural directives

legacy

*ngIf

legacy

Needs CommonModule or NgIf in imports.

<p *ngIf="user">Welcome</p>

*ngIf with else

legacy

<p *ngIf="user; else guest">Welcome</p>
<ng-template #guest><p>Sign in</p></ng-template>

*ngIf with then and else

legacy

<ng-container *ngIf="ok; then good; else bad" />

*ngIf as

legacy

<p *ngIf="user$ | async as user">{{ user.name }}</p>

*ngFor with trackBy

legacy

<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
// trackById(index: number, item: Item) { return item.id; }

*ngFor context variables

legacy

<li *ngFor="let x of list; index as i; first as isFirst; last as isLast">{{ i }}</li>

ngSwitch

legacy

<div [ngSwitch]="role">
  <app-admin *ngSwitchCase="'admin'" />
  <app-viewer *ngSwitchDefault />
</div>

ngClass and ngStyle

legacy

Plain [class] and [style] bindings cover the same ground with less overhead.

<div [ngClass]="{ active: isActive }" [ngStyle]="{ width: w + 'px' }"></div>

Two structural directives on one element

legacy

Only one structural directive per element, so wrap with ng-container.

<ng-container *ngIf="show">
  <li *ngFor="let x of list">{{ x }}</li>
</ng-container>

Signals

The reactive core of modern Angular: state, derivation, side effects, interop.

Creating and reading state

Writable signal

v16+

Calling the signal in a template registers a dependency.

count = signal(0);
// read
this.count();

Replace the value

v20+

this.count.set(10);

Derive from the previous value

v20+

this.count.update(c => c + 1);

Typed signal with an explicit type

v20+

user = signal<User | null>(null);

Custom equality

v16+

Skips notifying dependents when the comparison returns true.

user = signal(initial, { equal: (a, b) => a.id === b.id });

Expose a read-only view

v16+

Standard pattern for signal-based stores.

private _items = signal<Item[]>([]);
readonly items = this._items.asReadonly();

Update an array immutably

v20+

this.items.update(list => [...list, newItem]);
this.items.update(list => list.filter(i => i.id !== id));

Update an object immutably

v20+

this.form.update(f => ({ ...f, email: value }));

Derived state

computed

Computed signal

v16+

Lazy and memoized: it only recalculates when a dependency changed and something reads it.

total = computed(() => this.items().reduce((s, i) => s + i.price, 0));

Chained computeds

v16+

filtered = computed(() => this.items().filter(i => i.active));
count = computed(() => this.filtered().length);

Computed from an input

v16+

greeting = computed(() => `Hello, ${this.name()}`);

Writable derived state

v19+

Behaves like computed but can be overwritten, and resets when the source changes.

import { linkedSignal } from '@angular/core';

selected = linkedSignal(() => this.options()[0]);

linkedSignal with source and computation

v19+

Keeps the current selection if it still exists in the new list.

selectedId = linkedSignal({
  source: this.options,
  computation: (opts, prev) =>
    opts.find(o => o.id === prev?.value)?.id ?? opts[0]?.id,
});

Read without subscribing

v16+

The effect re-runs for userId only.

import { untracked } from '@angular/core';

effect(() => {
  const id = this.userId();
  const cfg = untracked(() => this.config());
});

Effects

side effects

Basic effect

v16+

Must run in an injection context, or be given an injector.

constructor() {
  effect(() => console.log('count is', this.count()));
}

Effect with cleanup

v16+

effect((onCleanup) => {
  const id = setInterval(() => this.tick(), 1000);
  onCleanup(() => clearInterval(id));
});

Effect created outside the constructor

v16+

private injector = inject(Injector);

start() {
  effect(() => this.sync(this.value()), { injector: this.injector });
}

Manually destroy an effect

v16+

const ref = effect(() => this.log());
ref.destroy();

Persist state to storage

v19+

Do not set other signals here; prefer computed or linkedSignal for derived state.

effect(() => localStorage.setItem('theme', this.theme()));

RxJS interop

@angular/core/rxjs-interop

Observable to signal

v16+

import { toSignal } from '@angular/core/rxjs-interop';

user = toSignal(this.userService.user$, { initialValue: null });

Require a synchronous first value

v16+

Works with BehaviorSubject or startWith.

state = toSignal(this.store.state$, { requireSync: true });

Signal to observable

v16+

import { toObservable } from '@angular/core/rxjs-interop';

query$ = toObservable(this.query);

Auto-unsubscribe

v16+

import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

constructor() {
  this.ws.messages$
    .pipe(takeUntilDestroyed())
    .subscribe(m => this.push(m));
}

Outside an injection context

v16+

private destroyRef = inject(DestroyRef);

load() {
  this.api.poll()
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe();
}

Debounce a signal without RxJS

experimental

Experimental in v22. It returns a Resource, not a signal, so read it with .value() and check .status() while the timer runs.

import { debounced, resource, signal } from '@angular/core';

query = signal('');
debouncedQuery = debounced(this.query, 300);

results = resource({
  params: () => this.debouncedQuery.value(),
  loader: ({ params }) => fetchResults(params),
});

Custom debounce timing

experimental

Pass a function returning a promise instead of a fixed duration.

debouncedQuery = debounced(this.query, (value, lastSnapshot) => {
  if (lastSnapshot.status === 'error') return;
  const ms = value.length < 3 ? 500 : 200;
  return new Promise<void>(r => setTimeout(r, ms));
});

Change detection controls

rendering

Zoneless change detection

v20+

Default for new v22 projects. Remove zone.js from polyfills as well.

bootstrapApplication(App, {
  providers: [provideZonelessChangeDetection()],
});

Mark an OnPush component dirty

Rarely needed once state lives in signals.

private cdr = inject(ChangeDetectorRef);
this.cdr.markForCheck();

Run change detection now

this.cdr.detectChanges();

Detach and reattach a view

this.cdr.detach();
this.cdr.reattach();

Keep work out of change detection

Zone-based apps only.

private zone = inject(NgZone);

this.zone.runOutsideAngular(() => {
  requestAnimationFrame(loop);
});

Force a full application tick

inject(ApplicationRef).tick();

Async & Resources

Signal-native data loading. Stable since v22.

The resource API

stable in v22

Promise based resource

v22+

Re-runs whenever any signal read inside params changes.

user = resource({
  params: () => ({ id: this.userId() }),
  loader: ({ params }) => fetchUser(params.id),
});

Read the state in a template

v22+

@if (user.isLoading()) {
  <app-spinner />
} @else if (user.error()) {
  <p>{{ user.error() }}</p>
} @else if (user.hasValue()) {
  <h1>{{ user.value().name }}</h1>
}

Cancel in-flight requests

v22+

abortSignal aborts the previous request when params change.

posts = resource({
  params: () => this.query(),
  loader: ({ params, abortSignal }) =>
    fetch(`/api/search?q=${params}`, { abortSignal }).then(r => r.json()),
});

Reload on demand

v22+

this.user.reload();

Locally override the value

v20+

The value signal is writable, which suits optimistic updates.

this.user.value.set(editedUser);

Available state signals

v22+

resource.value()      // T | undefined
resource.status()     // idle | loading | reloading | resolved | error | local
resource.isLoading()  // boolean
resource.hasValue()   // boolean narrowing guard
resource.error()      // unknown

Observable based resource

v22+

import { rxResource } from '@angular/core/rxjs-interop';

user = rxResource({
  params: () => this.userId(),
  stream: id => this.http.get<User>(`/api/users/${id}`),
});

HTTP resource

v22+

The shortest path from a URL signal to loading, error and value state.

import { httpResource } from '@angular/common/http';

user = httpResource<User>(() => `/api/users/${this.userId()}`);

httpResource with request options

v22+

results = httpResource<Result[]>(() => ({
  url: '/api/search',
  params: { q: this.query() },
  headers: { 'X-Scope': 'public' },
}));

Validate the response

v22+

Any parser works, for example a Zod schema.

user = httpResource(() => `/api/users/${this.id()}`, {
  parse: UserSchema.parse,
});

Skip loading until ready

v22+

Returning undefined leaves the resource idle.

user = httpResource<User>(() =>
  this.userId() ? `/api/users/${this.userId()}` : undefined
);

Directives

Behaviour you attach to elements, plus the built-ins worth knowing.

Writing directives

custom

Attribute directive

v17+

@Directive({
  selector: '[appHighlight]',
  host: { '(mouseenter)': 'on()', '(mouseleave)': 'off()' },
})
export class Highlight {
  private el = inject(ElementRef);
  color = input('#ffd9e2', { alias: 'appHighlight' });

  on() { this.el.nativeElement.style.background = this.color(); }
  off() { this.el.nativeElement.style.background = ''; }
}

Use it

<p [appHighlight]="'#ffd9e2'">Hover me</p>

Expose the instance to the template

@Directive({ selector: '[appTooltip]', exportAs: 'tooltip' })
export class Tooltip { open() {} }

// <div appTooltip #t="tooltip" (click)="t.open()"></div>

Structural directive

v17+

@Directive({ selector: '[appUnless]' })
export class Unless {
  private tpl = inject(TemplateRef<unknown>);
  private vcr = inject(ViewContainerRef);

  appUnless = input.required<boolean>();

  constructor() {
    effect(() => {
      this.vcr.clear();
      if (!this.appUnless()) this.vcr.createEmbeddedView(this.tpl);
    });
  }
}

// <p *appUnless="isHidden()">Visible</p>

Restrict where a directive applies

@Directive({ selector: 'input[appTrim], textarea[appTrim]' })
export class Trim {}

Built-in directives

@angular/common

Optimized images

priority sets fetchpriority high and preloads the LCP image. width and height are required.

import { NgOptimizedImage } from '@angular/common';

<img ngSrc="hero.jpg" width="1200" height="600" priority />

Responsive image sizes

<img ngSrc="card.jpg" width="400" height="300" sizes="(max-width: 600px) 100vw, 400px" />

Fill the parent container

The parent needs position relative and a size.

<div class="frame">
  <img ngSrc="bg.jpg" fill />
</div>

Render a component by class

<ng-container [ngComponentOutlet]="currentWidget()" />

Render a template

<ng-container [ngTemplateOutlet]="tpl" />

NgClass and NgStyle

legacy

<div [ngClass]="classes" [ngStyle]="styles"></div>

Plural and select messages

<p>{{ count | i18nPlural: { '=0': 'No items', '=1': 'One item', 'other': '# items' } }}</p>

Pipes

Format values in the template without touching the model.

Built-in pipes

@angular/common

Date

Presets: short, medium, long, full, plus the time and date only variants.

{{ createdAt | date }}
{{ createdAt | date:'dd MMM yyyy' }}
{{ createdAt | date:'short' }}
{{ createdAt | date:'medium':'UTC':'fr-FR' }}

Common date patterns

'yyyy-MM-dd'      2026-07-28
'dd/MM/yy HH:mm'  28/07/26 14:05
'EEEE'            Tuesday
'MMM d, y'        Jul 28, 2026

Currency

{{ price | currency }}
{{ price | currency:'EUR' }}
{{ price | currency:'EUR':'code' }}
{{ price | currency:'EUR':'symbol':'1.2-2' }}

Number and percent

The digit string is minIntegerDigits.minFraction-maxFraction.

{{ ratio | number:'1.0-2' }}
{{ ratio | percent:'1.0-1' }}

Case

{{ name | uppercase }}
{{ name | lowercase }}
{{ name | titlecase }}

Slice

{{ items | slice:0:5 }}
{{ text | slice:0:100 }}

JSON for debugging

<pre>{{ state() | json }}</pre>

Iterate an object

v17+

@for (entry of settings | keyvalue; track entry.key) {
  <li>{{ entry.key }}: {{ entry.value }}</li>
}

Async

v17+

Subscribes and unsubscribes for you.

{{ user$ | async }}
@if (user$ | async; as user) { {{ user.name }} }

Custom pipes

authoring

Pure pipe

Pure by default: it re-runs only when the input reference changes.

@Pipe({ name: 'truncate' })
export class Truncate implements PipeTransform {
  transform(value: string, limit = 40, suffix = '...'): string {
    return value.length > limit ? value.slice(0, limit) + suffix : value;
  }
}

Use it with arguments

{{ description | truncate:80:'…' }}

Impure pipe

Runs on every change detection cycle. Costly, so prefer a computed signal.

@Pipe({ name: 'filter', pure: false })

Inject a service inside a pipe

@Pipe({ name: 'localCurrency' })
export class LocalCurrency implements PipeTransform {
  private locale = inject(LOCALE_ID);
  transform(v: number) { return formatCurrency(v, this.locale, '€'); }
}

Register it

@Component({ imports: [Truncate] })

Dependency Injection

Providers, tokens, scopes and the injector tree.

Services and injection

Tree-shakable singleton

Removed from the bundle if nothing injects it.

@Injectable({ providedIn: 'root' })
export class UserService {}

Inject with the inject() function

Works in field initializers, constructors and factory functions.

export class UserList {
  private users = inject(UserService);
  private router = inject(Router);
}

Constructor injection

legacy

constructor(private users: UserService) {}

Provide at component level

Each instance of the component gets its own WizardState.

@Component({
  selector: 'app-wizard',
  providers: [WizardState],
})
export class Wizard {}

Hide a provider from projected content

viewProviders reaches the template but not content passed through ng-content.

@Component({ viewProviders: [PanelState] })

Application wide providers

bootstrapApplication(App, {
  providers: [
    provideHttpClient(),
    provideRouter(routes),
    { provide: API_URL, useValue: '/api' },
  ],
});

Tokens and provider recipes

providers

Injection token

export const API_URL = new InjectionToken<string>('API_URL');

// provide
{ provide: API_URL, useValue: 'https://api.example.com' }
// inject
private url = inject(API_URL);

Token with a default factory

export const CONFIG = new InjectionToken<Config>('CONFIG', {
  providedIn: 'root',
  factory: () => ({ retries: 3 }),
});

useClass

{ provide: Logger, useClass: ConsoleLogger }

useValue

{ provide: FEATURE_FLAGS, useValue: { beta: true } }

useFactory with dependencies

{
  provide: ApiClient,
  useFactory: () => new ApiClient(inject(API_URL)),
}

useExisting alias

{ provide: AbstractStore, useExisting: ConcreteStore }

Multi provider

Every multi registration for a token is collected into one array.

{ provide: VALIDATORS, useValue: emailRule, multi: true }

Resolution modifiers and scopes

injector tree

Optional dependency

Returns null instead of throwing.

private analytics = inject(Analytics, { optional: true });

Only this injector

private state = inject(PanelState, { self: true });

Start from the parent

private parentForm = inject(ControlContainer, { skipSelf: true });

Stop at the host element

private tabs = inject(TabGroup, { host: true });

Run code in an injection context

private injector = inject(EnvironmentInjector);

later() {
  runInInjectionContext(this.injector, () => {
    const http = inject(HttpClient);
  });
}

Run something at startup

v19+

Return a promise or observable and Angular waits for it.

provideAppInitializer(() => {
  const config = inject(ConfigService);
  return config.load();
})

APP_INITIALIZER

legacy

{
  provide: APP_INITIALIZER,
  useFactory: (c: ConfigService) => () => c.load(),
  deps: [ConfigService],
  multi: true,
}

Bring NgModule providers into a standalone app

providers: [importProvidersFrom(SomeLegacyModule)]

Routing

Route configuration, navigation, guards, resolvers and lazy loading.

Configuration

routes

Route table

Order matters: the first match wins, so the wildcard goes last.

export const routes: Routes = [
  { path: '', component: Home, title: 'Home' },
  { path: 'users/:id', component: UserDetail },
  { path: 'old', redirectTo: 'new', pathMatch: 'full' },
  { path: '**', component: NotFound },
];

Register the router

bootstrapApplication(App, {
  providers: [provideRouter(routes)],
});

Lazy load a component

{ path: 'admin', loadComponent: () => import('./admin').then(m => m.Admin) }

Lazy load child routes

{ path: 'shop', loadChildren: () => import('./shop.routes').then(m => m.SHOP_ROUTES) }

Child routes and a layout

{
  path: 'settings',
  component: SettingsLayout,
  children: [
    { path: '', redirectTo: 'profile', pathMatch: 'full' },
    { path: 'profile', component: Profile },
    { path: 'billing', component: Billing },
  ],
}

Static data and a dynamic title

{
  path: 'reports',
  component: Reports,
  data: { roles: ['admin'] },
  title: (route) => `Report ${route.params['id']}`,
}

Named outlet route

{ path: 'compose', component: Compose, outlet: 'modal' }

Links and outlets

template

Router outlet

<router-outlet />
<router-outlet name="modal" />

Link

<a routerLink="/users">Users</a>
<a [routerLink]="['/users', user.id]">Profile</a>

Link with query params and fragment

<a [routerLink]="['/search']"
   [queryParams]="{ q: 'angular', page: 2 }"
   fragment="results">Search</a>

Active link styling

<a routerLink="/home"
   routerLinkActive="is-active"
   [routerLinkActiveOptions]="{ exact: true }">Home</a>

Preserve or merge query params

Also accepts preserve.

<a routerLink="/next" queryParamsHandling="merge">Next</a>

Relative navigation in a link

<a [routerLink]="['../sibling']">Sibling</a>

Reading route state

ActivatedRoute

Bind route params straight to inputs

v17+

Path params, query params, data and resolved values all map to inputs.

provideRouter(routes, withComponentInputBinding())

// in the component
id = input.required<string>();

Params as signals

v16+

private route = inject(ActivatedRoute);
params = toSignal(this.route.paramMap);

Subscribe to params

Use this when the same component is reused across param changes.

this.route.paramMap.subscribe(p => this.load(p.get('id')!));

One-time snapshot read

const id = this.route.snapshot.paramMap.get('id');

Query params and fragment

this.route.queryParamMap.subscribe(q => this.page = Number(q.get('page') ?? 1));
const hash = this.route.snapshot.fragment;

Resolved data

this.route.data.subscribe(d => this.user = d['user']);

Navigation

Router

Navigate by commands

private router = inject(Router);
this.router.navigate(['/users', id]);

Navigate by URL string

this.router.navigateByUrl('/users/42?tab=billing');

With query params and fragment

this.router.navigate(['/search'], {
  queryParams: { q: term },
  fragment: 'top',
  queryParamsHandling: 'merge',
});

Relative navigation

this.router.navigate(['../edit'], { relativeTo: this.route });

Replace the history entry

this.router.navigate(['/login'], { replaceUrl: true });

Pass state that stays out of the URL

this.router.navigate(['/checkout'], { state: { cartId } });
// read: this.router.getCurrentNavigation()?.extras.state

React to router events

this.router.events
  .pipe(filter(e => e instanceof NavigationEnd))
  .subscribe(() => window.scrollTo(0, 0));

Guards and resolvers

functional

Can activate

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isLoggedIn() || router.createUrlTree(['/login']);
};

// { path: 'admin', component: Admin, canActivate: [authGuard] }

Can match, for lazy chunks

canMatch runs before the chunk downloads, so the code never loads for unauthorized users.

export const roleGuard: CanMatchFn = (route) => inject(Auth).hasRole('admin');

// { path: 'admin', loadComponent: ..., canMatch: [roleGuard] }

Can deactivate

export const dirtyGuard: CanDeactivateFn<FormPage> = (component) =>
  !component.isDirty() || confirm('Discard changes?');

Resolver

export const userResolver: ResolveFn<User> = (route) =>
  inject(UserService).byId(route.paramMap.get('id')!);

// { path: 'users/:id', component: UserDetail, resolve: { user: userResolver } }

Guard on child routes

v20+

{ path: 'admin', canActivateChild: [authGuard], children: [...] }

Router features

provideRouter(...)

Scroll restoration and anchor scrolling

provideRouter(routes,
  withInMemoryScrolling({
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled',
  }))

View transitions

v17+

Uses the browser View Transition API between navigations.

provideRouter(routes, withViewTransitions())

Preload lazy chunks

provideRouter(routes, withPreloading(PreloadAllModules))

Hash based URLs

provideRouter(routes, withHashLocation())

Bind route data to inputs

v16+

provideRouter(routes, withComponentInputBinding())

Log navigation events

provideRouter(routes, withDebugTracing())

Custom error handling

v17+

provideRouter(routes, withNavigationErrorHandler(e => inject(Logger).error(e)))

Module based setup

legacy

RouterModule.forRoot(routes)
RouterModule.forChild(childRoutes)

Signal Forms

The signal-native forms stack from @angular/forms/signals. Stable in v22.

Building a form

v22

Model plus form

v22+

The form structure is derived from the shape of the model signal.

import { signal } from '@angular/core';
import { form, FormField } from '@angular/forms/signals';

@Component({ imports: [FormField] })
export class Login {
  model = signal({ email: '', password: '' });
  loginForm = form(this.model);
}

Bind fields in the template

v20+

formField syncs the value plus required, disabled and readonly attributes.

<input [formField]="loginForm.email" />
<input type="password" [formField]="loginForm.password" />

Read field state

v20+

Every node of the tree exposes the same signals, including the root.

loginForm.email().value()
loginForm.email().valid()
loginForm.email().errors()
loginForm.email().touched()
loginForm.email().dirty()

Nested model

v16+

Field access is fully typed all the way down.

model = signal({
  name: '',
  address: { city: '', zip: '' },
});
profile = form(this.model);
// profile.address.city

Update the model directly

v20+

The field tree reacts automatically.

this.model.update(m => ({ ...m, email: 'new@example.com' }));

Validation

schema

Built-in validators

v22+

The second argument to form() is the schema function. Every rule takes an options object with message and an optional when.

import { form, required, email, minLength } from '@angular/forms/signals';

loginForm = form(this.model, (path) => {
  required(path.email, { message: 'Email is required' });
  email(path.email, { message: 'Enter a valid email' });
  minLength(path.password, 8, { message: 'At least 8 characters' });
});

Numeric and length bounds

v20+

min(path.age, 18, { message: 'You must be 18 or older' });
max(path.rating, 5, { message: 'Rating cannot exceed 5' });
minLength(path.bio, 10);
maxLength(path.bio, 500);

Dynamic bound from another signal

v20+

Pass a function instead of a literal to make the bound reactive.

min(path.participants, () => this.minimumRequired(), {
  message: 'Not enough participants',
});

Pattern

v20+

pattern is the one built-in that does not mirror to the native attribute.

pattern(path.phone, /^\d{3}-\d{3}-\d{4}$/, {
  message: 'Use the format 555-123-4567',
});

Custom rule

v20+

Return null when the field is valid.

validate(path.amount, ({ value }) => {
  const v = value();
  if (v <= 0) return { kind: 'min', message: 'Must be greater than zero' };
  return null;
});

Compare against another field

v20+

validate(path.confirm, ({ value, valueOf }) =>
  value() === valueOf(path.password)
    ? null
    : { kind: 'match', message: 'Passwords do not match' }
);

Conditional rule

v20+

required(path.promoCode, {
  message: 'Promo code is required',
  when: ({ valueOf }) => valueOf(path.applyDiscount),
});

Validate every item in an array

v22+

applyEach(path.items, (item) => {
  required(item.name, { message: 'Item name is required' });
  min(item.quantity, 1);
});

Apply a group of rules conditionally

v22+

applyWhen(
  path,
  ({ valueOf }) => valueOf(path.type) === 'business',
  (p) => required(p.vatNumber)
);

Async validation

v22+

onError is required, not optional.

validateAsync(path.username, {
  params: ({ value }) => value(),
  factory: (username) => resource({
    params: username,
    loader: ({ params }) => api.isTaken(params),
  }),
  onError: () => ({ kind: 'taken', message: 'Username is taken' }),
});

HTTP validation

v22+

onSuccess maps the response to an error or null. onError handles the request failing.

validateHttp(path.username, {
  request: ({ value }) => `/api/check-username?username=${value()}`,
  onSuccess: (res: any) =>
    res.taken ? { kind: 'taken', message: 'Username is taken' } : null,
  onError: () => ({ kind: 'network', message: 'Could not verify username' }),
});

Validate across a whole subtree

v22+

Lets one rule report an error against a different field.

validateTree(path, (ctx) => {
  if (ctx.valueOf(path.firstName).length < 5) {
    return {
      kind: 'minLength5',
      message: 'First name is too short',
      fieldTree: ctx.fieldTree.lastName,
    };
  }
  return null;
});

Use a Zod or Valibot schema

v22+

Any library implementing the Standard Schema spec works.

import { validateStandardSchema } from '@angular/forms/signals';
import * as z from 'zod';

const userSchema = z.object({
  email: z.email(),
  password: z.string().min(8),
});

userForm = form(this.model, (path) => {
  validateStandardSchema(path, userSchema);
});

Reusable custom rule

v20+

function url(path: SchemaPath<string>, options?: { message?: string }) {
  validate(path, ({ value }) => {
    try { new URL(value()); return null; }
    catch { return { kind: 'url', message: options?.message ?? 'Enter a valid URL' }; }
  });
}

// then: url(path.website, { message: 'Bad website' });

Reusable schema

v20+

const addressSchema = schema<Address>((path) => {
  required(path.city);
  required(path.zip);
});

checkout = form(this.model, (path) => {
  apply(path.shipping, addressSchema);
});

Field behaviour and submission

rules

Disable, hide, make read-only

v20+

disabled(path.discount, ({ valueOf }) => !valueOf(path.isMember));
readonly(path.id);
hidden(path.internalNote, () => !this.isAdmin());

Debounce a field

v20+

debounce(path.search, 300);

Submit

v22+

The second argument is an options object with an action function, not a bare callback.

import { submit } from '@angular/forms/signals';

onSubmit(event: Event) {
  event.preventDefault();
  submit(this.loginForm, {
    action: async () => {
      await this.api.login(this.model());
    },
  });
}

Show errors only after interaction

v17+

@if (loginForm.email().touched() && loginForm.email().errors().length) {
  @for (err of loginForm.email().errors(); track err.kind) {
    <p class="error">{{ err.message }}</p>
  }
}

Disable submit while invalid

v20+

<button [disabled]="loginForm().invalid() || loginForm().submitting()">
  Save
</button>

Reactive & Template Forms

The long-standing forms APIs, still fully supported.

Reactive forms

ReactiveFormsModule

Build a form group

private fb = inject(FormBuilder);

form = this.fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', Validators.minLength(8)],
});

Non-nullable controls

Without this, reset() sets controls back to null.

form = this.fb.nonNullable.group({
  name: ['', Validators.required],
});

Bind it in the template

<form [formGroup]="form" (ngSubmit)="submit()">
  <input formControlName="email" />
  <button [disabled]="form.invalid">Send</button>
</form>

Standalone control

search = new FormControl('', { nonNullable: true });
<input [formControl]="search" />

Nested group

form = this.fb.group({
  address: this.fb.group({ city: [''], zip: [''] }),
});
// <div formGroupName="address"><input formControlName="city" /></div>

Form array

form = this.fb.group({ tags: this.fb.array([this.fb.control('')]) });

get tags() { return this.form.get('tags') as FormArray; }
addTag() { this.tags.push(this.fb.control('')); }
removeTag(i: number) { this.tags.removeAt(i); }

Render a form array

v17+

<div formArrayName="tags">
  @for (c of tags.controls; track $index) {
    <input [formControlName]="$index" />
  }
</div>

Values, state and validators

control API

Read and write values

setValue requires every control; patchValue does not.

this.form.value
this.form.getRawValue()   // includes disabled controls
this.form.setValue({ email: 'a@b.c', password: 'secret12' });
this.form.patchValue({ email: 'a@b.c' });

Reset

this.form.reset();
this.form.reset({ email: 'default@example.com' });

Control state flags

c.valid  c.invalid  c.pending
c.touched  c.untouched
c.dirty  c.pristine
c.disabled  c.enabled

Enable and disable

this.form.controls.email.disable();
this.form.controls.email.enable();

Mark for display

this.form.markAllAsTouched();
this.form.controls.email.markAsDirty();

Watch changes

v16+

this.form.valueChanges
  .pipe(debounceTime(300), takeUntilDestroyed())
  .subscribe(v => this.save(v));

this.form.statusChanges.subscribe(s => console.log(s));

Value changes as a signal

v16+

value = toSignal(this.form.valueChanges, { initialValue: this.form.value });

Built-in validators

Validators.required
Validators.requiredTrue
Validators.email
Validators.min(1)  Validators.max(99)
Validators.minLength(3)  Validators.maxLength(50)
Validators.pattern(/^[a-z]+$/)

Custom validator

export function noSpaces(): ValidatorFn {
  return (c: AbstractControl): ValidationErrors | null =>
    /\s/.test(c.value ?? '') ? { noSpaces: true } : null;
}

Cross-field validator

const match: ValidatorFn = (g) =>
  g.get('password')!.value === g.get('confirm')!.value ? null : { mismatch: true };

this.fb.group({ ... }, { validators: match });

Async validator

export function uniqueEmail(api: Api): AsyncValidatorFn {
  return (c) => api.check(c.value).pipe(
    map(taken => (taken ? { taken: true } : null))
  );
}

Change the update trigger

Also accepts change (default) and submit.

new FormControl('', { updateOn: 'blur' })

Show an error message

v17+

@if (form.controls.email.touched && form.controls.email.hasError('required')) {
  <p class="error">Email is required</p>
}

Template-driven forms

FormsModule

Basic form

v17+

name is required for ngModel to register the control.

<form #f="ngForm" (ngSubmit)="save(f.value)">
  <input name="email" ngModel required email #email="ngModel" />
  @if (email.touched && email.invalid) {
    <p>Enter a valid email</p>
  }
  <button [disabled]="f.invalid">Save</button>
</form>

Two-way binding

<input [(ngModel)]="user.name" name="name" />

Group fields

<div ngModelGroup="address">
  <input name="city" ngModel />
</div>

Standalone ngModel outside a form

<input [(ngModel)]="query" [ngModelOptions]="{ standalone: true }" />

CSS state classes

Angular adds these to every control element.

.ng-valid .ng-invalid
.ng-touched .ng-untouched
.ng-dirty .ng-pristine
.ng-pending

Custom form controls

ControlValueAccessor

Implement the interface

Lets your component be used with formControlName or ngModel.

@Component({
  selector: 'app-rating',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => Rating),
    multi: true,
  }],
  template: `...`,
})
export class Rating implements ControlValueAccessor {
  value = 0;
  onChange = (v: number) => {};
  onTouched = () => {};

  writeValue(v: number) { this.value = v; }
  registerOnChange(fn: any) { this.onChange = fn; }
  registerOnTouched(fn: any) { this.onTouched = fn; }
  setDisabledState(isDisabled: boolean) { }
}

HttpClient

Requests, params, interceptors and error handling.

Setup

providers

Provide the client

bootstrapApplication(App, {
  providers: [provideHttpClient()],
});

Use the fetch backend

v16+

Recommended, and required for streaming responses under SSR.

provideHttpClient(withFetch())

Register interceptors

v16+

provideHttpClient(
  withFetch(),
  withInterceptors([authInterceptor, retryInterceptor]),
)

Class based interceptors

legacy

provideHttpClient(withInterceptorsFromDi())

Enable JSONP

provideHttpClient(withJsonpSupport())

Making requests

verbs

GET with a typed response

Nothing happens until something subscribes.

private http = inject(HttpClient);

getUsers() {
  return this.http.get<User[]>('/api/users');
}

POST, PUT, PATCH, DELETE

this.http.post<User>('/api/users', body);
this.http.put<User>(`/api/users/${id}`, body);
this.http.patch<User>(`/api/users/${id}`, partial);
this.http.delete<void>(`/api/users/${id}`);

Query parameters

Plain objects work; HttpParams is only needed for incremental building.

this.http.get<Result[]>('/api/search', {
  params: { q: term, page: 2, tags: ['a', 'b'] },
});

Build params immutably

HttpParams is immutable, so reassign the result.

let params = new HttpParams();
params = params.set('q', term).append('tag', 'new');

Headers

this.http.get('/api/me', {
  headers: new HttpHeaders({ Authorization: `Bearer ${token}` }),
});

Read the full response

this.http.get<User>('/api/me', { observe: 'response' })
  .subscribe(r => console.log(r.status, r.headers, r.body));

Non-JSON responses

this.http.get('/report.pdf', { responseType: 'blob' });
this.http.get('/notes.txt', { responseType: 'text' });

Upload with progress

this.http.post('/api/upload', formData, {
  reportProgress: true,
  observe: 'events',
}).subscribe(e => {
  if (e.type === HttpEventType.UploadProgress) {
    this.percent = Math.round(100 * e.loaded / (e.total ?? 1));
  }
});

Send credentials

this.http.get('/api/me', { withCredentials: true });

Interceptors

functional

Attach a token

HttpRequest is immutable, so always clone it.

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  if (!token) return next(req);
  return next(req.clone({
    setHeaders: { Authorization: `Bearer ${token}` },
  }));
};

Handle errors centrally

export const errorInterceptor: HttpInterceptorFn = (req, next) =>
  next(req).pipe(
    catchError((e: HttpErrorResponse) => {
      if (e.status === 401) inject(Router).navigate(['/login']);
      return throwError(() => e);
    })
  );

Show a loading indicator

export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
  const bar = inject(LoadingBar);
  bar.start();
  return next(req).pipe(finalize(() => bar.stop()));
};

Skip an interceptor per request

v20+

export const SKIP_AUTH = new HttpContextToken(() => false);

this.http.get('/public', { context: new HttpContext().set(SKIP_AUTH, true) });

// inside the interceptor
if (req.context.get(SKIP_AUTH)) return next(req);

Errors and retries

resilience

Catch and recover

this.http.get<User[]>('/api/users').pipe(
  catchError(err => {
    console.error(err.status, err.message);
    return of([]);
  })
);

Retry with a delay

this.http.get('/api/flaky').pipe(retry({ count: 3, delay: 1000 }));

Inspect the error

catchError((e: HttpErrorResponse) => {
  const clientSide = e.error instanceof ProgressEvent;
  return throwError(() => new Error(clientSide ? 'Network error' : e.error?.message));
})

Timeout

this.http.get('/api/slow').pipe(timeout(5000));

RxJS in Angular

The operators that actually show up in Angular codebases.

Creating streams

creation

From values

of(1, 2, 3)
from([1, 2, 3])
from(fetch('/api'))

Time based

interval(1000)
timer(500, 1000)

From DOM events

fromEvent(window, 'resize')

Empty and error

EMPTY
throwError(() => new Error('failed'))

Subjects

BehaviorSubject always has a current value, which suits state.

const s = new Subject<string>();
const b = new BehaviorSubject<string>('initial');
const r = new ReplaySubject<string>(2);

Transforming

map & flatten

Map values

source$.pipe(map(u => u.name))

Cancel the previous inner stream

The right choice for type-ahead search and route param driven loads.

this.query$.pipe(switchMap(q => this.api.search(q)))

Queue in order

Preserves order, one at a time.

this.saves$.pipe(concatMap(v => this.api.save(v)))

Run in parallel

this.ids$.pipe(mergeMap(id => this.api.load(id)))

Ignore while one is running

Prevents double submits on a button.

this.clicks$.pipe(exhaustMap(() => this.api.submit()))

Accumulate

this.events$.pipe(scan((acc, e) => [...acc, e], [] as Event[]))

Filtering and limiting

filter

Filter

source$.pipe(filter(u => u.active))

Wait for a pause in input

this.input$.pipe(debounceTime(300), distinctUntilChanged())

Rate limit

this.scroll$.pipe(throttleTime(100))

Take a fixed number

source$.pipe(take(1))
source$.pipe(first())

Stop on a signal

source$.pipe(takeUntil(this.destroy$))

Stop when the component is destroyed

v16+

Replaces the manual destroy$ subject pattern.

source$.pipe(takeUntilDestroyed())

Skip early emissions

source$.pipe(skip(1))

Combining

join

Latest from each, on every emission

Waits until every source has emitted once.

combineLatest([this.user$, this.settings$])

Wait for all to complete

Like Promise.all. Nothing emits if one source never completes.

forkJoin({ user: this.api.user(), roles: this.api.roles() })

Interleave

merge(this.a$, this.b$)

One after another

concat(this.first$, this.second$)

Sample another stream on demand

this.submit$.pipe(withLatestFrom(this.form$))

Seed the stream

this.value$.pipe(startWith(null))

Errors and utilities

control

Recover

source$.pipe(catchError(() => of(fallback)))

Retry with backoff

source$.pipe(retry({ count: 3, delay: (_, n) => timer(n * 1000) }))

Always run cleanup

source$.pipe(finalize(() => this.loading.set(false)))

Side effect without changing the stream

source$.pipe(tap(v => console.log(v)))

Share one subscription

Stops every subscriber from firing its own request.

this.config$ = this.http.get('/config').pipe(shareReplay({ bufferSize: 1, refCount: true }));

Unsubscribe manually

private sub = source$.subscribe();
ngOnDestroy() { this.sub.unsubscribe(); }

Testing

Component, service and HTTP tests. Vitest is the default runner in v22.

Component tests

TestBed

Set up and create

experimental

Standalone components go in imports, not declarations.

describe('UserCard', () => {
  let fixture: ComponentFixture<UserCard>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [UserCard],
      providers: [{ provide: UserService, useValue: stub }],
    }).compileComponents();

    fixture = TestBed.createComponent(UserCard);
    fixture.detectChanges();
  });
});

Set a signal input

fixture.componentRef.setInput('user', mockUser);
fixture.detectChanges();

Query the DOM

const el = fixture.nativeElement as HTMLElement;
expect(el.querySelector('h2')?.textContent).toContain('Ada');

Query with DebugElement

const btn = fixture.debugElement.query(By.css('button.save'));
btn.triggerEventHandler('click');
fixture.detectChanges();

Find a child component

const child = fixture.debugElement.query(By.directive(Avatar));

Await pending work

await fixture.whenStable();

Let the fixture detect changes for you

Saves calling detectChanges() after every state change.

fixture.autoDetectChanges();

Services and dependencies

injection

Get a service

const service = TestBed.inject(UserService);

Spy on a method

const spy = spyOn(service, 'load').and.returnValue(of([mockUser]));
expect(spy).toHaveBeenCalledWith(1);

Full spy object

const api = jasmine.createSpyObj('Api', ['load', 'save']);
api.load.and.returnValue(of([]));

Override a provider

TestBed.overrideProvider(Config, { useValue: { apiUrl: '/test' } });

Async testing

timing

fakeAsync and tick

it('debounces', fakeAsync(() => {
  component.search('ang');
  tick(300);
  expect(component.results()).toHaveLength(2);
}));

Flush all pending timers

flush();
discardPeriodicTasks();

waitForAsync

it('loads', waitForAsync(() => {
  fixture.whenStable().then(() => expect(...));
}));

Plain async and await

it('loads', async () => {
  await fixture.whenStable();
  expect(component.ready()).toBe(true);
});

HTTP and router tests

harnesses

Mock the HTTP backend

TestBed.configureTestingModule({
  providers: [provideHttpClient(), provideHttpClientTesting()],
});

const httpMock = TestBed.inject(HttpTestingController);

Assert and flush a request

service.getUsers().subscribe(u => expect(u.length).toBe(1));

const req = httpMock.expectOne('/api/users');
expect(req.request.method).toBe('GET');
req.flush([mockUser]);

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

Simulate an error

req.flush('Not found', { status: 404, statusText: 'Not Found' });

Route driven component test

v16+

TestBed.configureTestingModule({ providers: [provideRouter(routes)] });

const harness = await RouterTestingHarness.create();
const cmp = await harness.navigateByUrl('/users/1', UserDetail);

Errors & Debugging

Catching what breaks, and the console tools for working out why.

Error handling

runtime

Custom global handler

Angular routes anything it catches on your behalf here, such as errors thrown in lifecycle hooks.

@Injectable()
export class AppErrorHandler implements ErrorHandler {
  private logger = inject(LoggerService);

  handleError(error: unknown) {
    this.logger.report(error);
  }
}

// providers: [{ provide: ErrorHandler, useClass: AppErrorHandler }]

Catch errors from outside Angular

v20+

Adds window error and unhandledrejection listeners and forwards both to ErrorHandler. Included by default in new v20+ projects.

providers: [provideBrowserGlobalErrorListeners()]

ErrorHandler does not see HTTP failures

// Use an interceptor for those
export const errorInterceptor: HttpInterceptorFn = (req, next) =>
  next(req).pipe(catchError(e => { inject(Logger).http(e); return throwError(() => e); }));

Errors Angular does not catch

Angular only intercepts code that the framework itself invoked.

// Anything you call directly from your own code.
// Wrap it in try/catch yourself.

Let a test assert on an unhandled error

v20+

TestBed.configureTestingModule({ rethrowApplicationErrors: false });

Console debugging

DevTools

Inspect the selected element's component

Available in development builds. $0 is whatever you last selected in the Elements panel.

// select a node in Elements, then in the console:
ng.getComponent($0)

Read the template context

v17+

Gives you the @for item, index and friends.

ng.getContext($0)

List directives on an element

ng.getDirectives($0)
ng.getOwningComponent($0)
ng.getHostElement(component)

Push a change through after editing state

const c = ng.getComponent($0);
c.count.set(42);
ng.applyChanges(c);

Measure change detection

ng.profiler.timeChangeDetection()

Angular DevTools

// Chrome and Firefox extension.
// Components tab: inspect the tree and edit state live.
// Profiler tab: record change detection.
// Signal graph: see what depends on what.

Build and bundle analysis

tooling

Produce a stats file

ng build --stats-json

Inspect it

npx esbuild-visualizer --metadata dist/my-app/stats.json
// or upload the file to a bundle analyzer of your choice

Find what pulled a package in

npm ls some-package

Type-check without emitting

npx tsc --noEmit -p tsconfig.app.json

Verbose build diagnostics

ng build --verbose

Security

What Angular protects you from, and where you are on your own.

Sanitization

XSS

Interpolation is always escaped

This is the default and it is why most Angular templates are XSS-safe for free.

<p>{{ userInput }}</p>
<!-- <script> arrives as visible text, never as markup -->

innerHTML is sanitized, not trusted

Angular strips script tags and event handler attributes, and logs a warning when it does.

<div [innerHTML]="userHtml"></div>

Explicitly trust a value

Only ever call this on a value you constructed, never on anything a user supplied.

import { DomSanitizer } from '@angular/platform-browser';

private sanitizer = inject(DomSanitizer);

safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.embedUrl);

The bypass methods

bypassSecurityTrustHtml(value)
bypassSecurityTrustStyle(value)
bypassSecurityTrustScript(value)
bypassSecurityTrustUrl(value)
bypassSecurityTrustResourceUrl(value)

Sanitize by hand

import { SecurityContext } from '@angular/core';

const clean = this.sanitizer.sanitize(SecurityContext.HTML, dirty);

Transport and policy

hardening

XSRF token handling

HttpClient reads the cookie and echoes it as a header on mutating requests.

provideHttpClient(
  withXsrfConfiguration({
    cookieName: 'XSRF-TOKEN',
    headerName: 'X-XSRF-TOKEN',
  }),
)

Turn XSRF handling off

Only when another mechanism already covers it.

provideHttpClient(withNoXsrfProtection())

Content Security Policy nonce

v20+

Lets Angular attach your per-request nonce to the styles it injects.

<app-root ngCspNonce="{{ requestNonce }}"></app-root>

Rules that matter more than any API

// Never build templates by concatenating user input.
// Keep Angular and its dependencies patched.
// Validate on the server as well as the client.
// Treat bypassSecurityTrust* as a code-review trigger.

SSR & Performance

Server rendering, hydration and the levers that move real metrics.

Server-side rendering

@angular/ssr

Add SSR to an app

v20+

Creates the server entry point and a build target.

ng add @angular/ssr

Enable hydration

v16+

Reuses the server markup instead of re-rendering it.

bootstrapApplication(App, {
  providers: [provideClientHydration()],
});

Replay events captured before hydration

v19+

Clicks made during hydration are not lost.

provideClientHydration(withEventReplay())

Incremental hydration

v19+

Enabled by default for new v22 apps.

provideClientHydration(withIncrementalHydration())

// template
@defer (hydrate on viewport) { <app-grid /> }

Per-route render mode

v19+

Prerender at build time, render per request, or leave it to the browser.

// app.routes.server.ts
import { RenderMode, ServerRoute } from '@angular/ssr';

export const serverRoutes: ServerRoute[] = [
  { path: '', renderMode: RenderMode.Prerender },
  { path: 'dashboard', renderMode: RenderMode.Client },
  { path: '**', renderMode: RenderMode.Server },
];

Register the server routes

v20+

Angular 19 used provideServerRouting(serverRoutes) instead. From v20 it is a feature of provideServerRendering.

// app.config.server.ts
import { provideServerRendering, withRoutes } from '@angular/ssr';
import { serverRoutes } from './app.routes.server';

const serverConfig: ApplicationConfig = {
  providers: [provideServerRendering(withRoutes(serverRoutes))],
};

App shell for the client-rendered route

v20+

provideServerRendering(
  withRoutes(serverRoutes),
  withAppShell(AppShell),
)

Custom headers and status per route

v19+

{
  path: 'profile',
  renderMode: RenderMode.Server,
  headers: { 'X-Custom': 'value' },
  status: 201,
}

Guard browser-only code

private platformId = inject(PLATFORM_ID);

if (isPlatformBrowser(this.platformId)) {
  localStorage.setItem('seen', '1');
}

DOM work that is safe under SSR

v16+

Never runs on the server.

afterNextRender(() => this.initMap());

Carry state from server to client

Avoids a duplicate request during hydration.

const KEY = makeStateKey<User>('user');

private state = inject(TransferState);
this.state.set(KEY, user);      // server
const u = this.state.get(KEY, null);  // client

Performance levers

speed

Zoneless application

v20+

Removes the zone.js polyfill and only checks views tied to signals.

provideZonelessChangeDetection()

OnPush everywhere

v20+

Already the default in v22.

changeDetection: ChangeDetectionStrategy.OnPush

Defer below-the-fold work

v17+

@defer (on viewport) { <app-related /> }

Stable track expressions

v17+

A bad track key forces Angular to recreate every DOM node.

@for (row of rows(); track row.id) { }

Preload lazy routes after startup

provideRouter(routes, withPreloading(PreloadAllModules))

Prioritize the LCP image

<img ngSrc="hero.jpg" width="1440" height="720" priority />

Set bundle budgets

The build fails when a bundle crosses the error threshold.

// angular.json
"budgets": [
  { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" },
  { "type": "anyComponentStyle", "maximumWarning": "4kB" }
]

Keep expensive work out of templates

v16+

// avoid: {{ heavyCalculation() }} called on every check
total = computed(() => heavyCalculation(this.rows()));

Internationalization

Marking text, extracting messages and building per-locale bundles.

Setup and marking text

@angular/localize

Add the package

ng add @angular/localize

Mark an element for translation

<h1 i18n>Welcome back</h1>

Add meaning, description and a stable id

Format is meaning|description@@id. A custom id keeps the translation stable when the text changes.

<h1 i18n="site header|Greeting shown after login@@homeWelcome">
  Welcome back
</h1>

Translate an attribute

Prefix the attribute with i18n- to mark it.

<img [src]="logo" i18n-alt alt="Company logo" />
<button i18n-title title="Save the draft">Save</button>

Translate text with no wrapper element

<ng-container i18n>Terms apply</ng-container>

Mark a string in TypeScript

The :name: suffix labels the placeholder for translators.

const message = $localize`Welcome back`;
const greeting = $localize`Hello ${name}:userName:`;

Skip a block

Only elements you explicitly mark are extracted.

<div i18n-#no>...</div>
<!-- or simply leave the element unmarked -->

Plurals and alternatives

ICU

Plural

<span i18n>{count, plural,
  =0 {no items}
  =1 {one item}
  other {{{count}} items}
}</span>

Select

<span i18n>{gender, select,
  male {he}
  female {she}
  other {they}
}</span>

Pipe equivalents

{{ count | i18nPlural: pluralMap }}
{{ gender | i18nSelect: selectMap }}

Extract, configure, build

workflow

Extract messages

Produces messages.xlf. Hand that to translators, then keep messages.fr.xlf and friends alongside it.

ng extract-i18n --output-path src/locale

Choose a format

ng extract-i18n --format=json
// xlf | xlf2 | xmb | json | arb

Declare locales in angular.json

"i18n": {
  "sourceLocale": "en-US",
  "locales": {
    "fr": "src/locale/messages.fr.xlf",
    "de": { "translation": "src/locale/messages.de.xlf", "baseHref": "/de/" }
  }
}

Build every locale

Emits one bundle per locale into separate folders.

ng build --localize

Serve a single locale while developing

ng serve --configuration=fr

Set the runtime locale

Drives the date, currency, number and percent pipes.

import { LOCALE_ID } from '@angular/core';

providers: [{ provide: LOCALE_ID, useValue: 'fr-FR' }]

Register locale data for pipes

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

registerLocaleData(localeFr, 'fr');

Angular Aria

Headless accessible primitives. Stable in v22.

Getting started

v22

Install

v22+

Not bundled with the framework, so install it before importing anything.

npm install @angular/aria

What it gives you

v20+

The directives are headless: they ship no styles at all.

// Keyboard interaction, focus management, ARIA roles
// and states, wired for you.
// You still own the markup and every pixel of CSS.

Style from the ARIA state

v20+

Because the directives set the ARIA attributes, they double as your styling hooks.

[aria-selected='true'] { background: #e8f0fe; }
[aria-expanded='true'] .icon { transform: rotate(deg); }
[aria-disabled='true'] { opacity: .5; }

Listbox and options

selection

Single-select list

v22+

value is a model signal, so it two-way binds.

import { Listbox, Option } from '@angular/aria/listbox';

@Component({
  imports: [Listbox, Option],
  template: `
    <div ngListbox [(value)]="selected">
      @for (opt of options; track opt) {
        <div ngOption [value]="opt">{{ opt }}</div>
      }
    </div>
  `,
})
export class Picker {
  options = ['Draft', 'Review', 'Published'];
  selected = signal<string[]>([]);
}

Multi-select and explicit selection

v22+

With explicit mode the user presses Space or Enter to select, rather than selection following focus.

<div ngListbox multi selectionMode="explicit">

Other patterns

directives

Accordion

v22+

import {
  AccordionGroup, AccordionTrigger, AccordionPanel, AccordionContent,
} from '@angular/aria/accordion';

<div ngAccordionGroup>
  <button ngAccordionTrigger value="one">Shipping</button>
  <div ngAccordionPanel value="one">
    <ng-template ngAccordionContent>Panel body</ng-template>
  </div>
</div>

Tabs

v22+

import { Tabs, TabList, Tab, TabPanel } from '@angular/aria/tabs';

<div ngTabs>
  <div ngTabList>
    <button ngTab value="a">Overview</button>
    <button ngTab value="b">Activity</button>
  </div>
  <div ngTabPanel value="a">...</div>
</div>

Combobox

v22+

The building block behind the select, multiselect and autocomplete patterns.

import {
  Combobox, ComboboxInput, ComboboxPopup, ComboboxPopupContainer,
} from '@angular/aria/combobox';

Available entry points

v22+

@angular/aria/accordion
@angular/aria/combobox
@angular/aria/grid
@angular/aria/listbox
@angular/aria/menu
@angular/aria/tabs
@angular/aria/toolbar
@angular/aria/tree

Works as a Signal Forms control

v22+

formField recognizes directives that expose a value model, so Aria controls bind like native inputs.

<div ngListbox [formField]="orderForm.status"></div>

Animations

Native CSS animations replaced the animations package in v20.2.

Enter and leave

current

Animate an element into the DOM

v20+

Angular adds the class, then removes it when the animation finishes.

<div animate.enter="fade-in">New row</div>

/* css */
.fade-in { animation: fade 200ms ease-out; }
@keyframes fade { from { opacity: 0 } to { opacity: 1 } }

Animate an element out

v20+

Angular waits for the animation to end before removing the node.

<div animate.leave="fade-out">Removing</div>

Bind the class name

v20+

<div [animate.enter]="enterClass()" [animate.leave]="'slide-out'"></div>

Multiple classes

v20+

<div animate.enter="fade-in slide-up"></div>

Bind on the host

v20+

@Component({
  host: {
    '[animate.enter]': "'fade-in'",
    '[animate.leave]': "'fade-out'",
  },
})
export class Toast {}

Hand off to a JS animation library

v20+

Calling animationComplete() is required when you take over the leave animation.

<div (animate.leave)="onLeave($event)"></div>

onLeave(event: any) {
  const anim = event.target.animate(
    [{ opacity: 1 }, { opacity: 0 }],
    { duration: 240, fill: 'forwards' }
  );
  anim.addEventListener('finish', () => event.animationComplete());
}

Legacy animations

deprecated

Provide the animations engine

legacy

@angular/animations is deprecated as of v20.2.

providers: [provideAnimationsAsync()]

Trigger, state and transition

legacy

@Component({
  animations: [
    trigger('openClose', [
      state('open', style({ height: '*', opacity: 1 })),
      state('closed', style({ height: 0, opacity: 0 })),
      transition('open <=> closed', animate('250ms ease')),
    ]),
  ],
})
// <div [@openClose]="isOpen() ? 'open' : 'closed'"></div>

Enter and leave aliases

legacy

transition(':enter', [style({ opacity: 0 }), animate('200ms')]),
transition(':leave', animate('200ms', style({ opacity: 0 }))),

Stagger a list

legacy

transition('* => *', [
  query(':enter', stagger('60ms', animate('200ms', style({ opacity: 1 })))),
])

Elements & PWA

Shipping Angular components as custom elements, and service worker basics.

Angular Elements

custom elements

Add the package

ng add @angular/elements

Define a custom element

import { createCustomElement } from '@angular/elements';

const app = await createApplication({
  providers: [provideHttpClient()],
});

const element = createCustomElement(RatingWidget, {
  injector: app.injector,
});
customElements.define('rating-widget', element);

Use it anywhere

Inputs become attributes and properties. Outputs become DOM CustomEvents.

<rating-widget value="4"></rating-widget>
<script>
  document.querySelector('rating-widget')
    .addEventListener('rated', e => console.log(e.detail));
</script>

Allow unknown tags inside Angular templates

@Component({ schemas: [CUSTOM_ELEMENTS_SCHEMA] })

Service workers

@angular/pwa

Add PWA support

Adds the service worker, a manifest and icons, and wires ngsw-config.json.

ng add @angular/pwa

Register the service worker

provideServiceWorker('ngsw-worker.js', {
  enabled: !isDevMode(),
  registrationStrategy: 'registerWhenStable:30000',
})

Prompt the user to reload on a new version

v22+

private updates = inject(SwUpdate);

constructor() {
  this.updates.versionUpdates
    .pipe(filter(e => e.type === 'VERSION_READY'), takeUntilDestroyed())
    .subscribe(() => {
      if (confirm('A new version is available. Reload?')) {
        document.location.reload();
      }
    });
}

Check for an update on demand

const found = await this.updates.checkForUpdate();
if (found) await this.updates.activateUpdate();

Guard against a disabled worker

isEnabled is false in development and when the browser has no service worker support.

if (this.updates.isEnabled) { ... }

Push notifications

private push = inject(SwPush);

const sub = await this.push.requestSubscription({
  serverPublicKey: VAPID_PUBLIC_KEY,
});
this.push.messages.subscribe(m => console.log(m));

Cache rules live in ngsw-config.json

{
  "dataGroups": [{
    "name": "api",
    "urls": ["/api/**"],
    "cacheConfig": {
      "strategy": "freshness",
      "maxSize": 100,
      "maxAge": "1h",
      "timeout": "5s"
    }
  }]
}

NgModules

The module architecture, for codebases that still run on it.

Module basics

legacy

Declare a module

legacy

@NgModule({
  declarations: [AppComponent, UserCard],
  imports: [BrowserModule, CommonModule, HttpClientModule],
  providers: [UserService],
  exports: [UserCard],
  bootstrap: [AppComponent],
})
export class AppModule {}

Bootstrap a module app

legacy

The standalone equivalent is bootstrapApplication.

platformBrowserDynamic().bootstrapModule(AppModule);

Feature module with routing

legacy

@NgModule({
  imports: [CommonModule, RouterModule.forChild(routes)],
})
export class AdminModule {}

Shared module pattern

legacy

@NgModule({
  imports: [CommonModule],
  declarations: [Truncate],
  exports: [CommonModule, FormsModule, Truncate],
})
export class SharedModule {}

Configurable module

legacy

static forRoot(config: Config): ModuleWithProviders<CoreModule> {
  return { ngModule: CoreModule, providers: [{ provide: CONFIG, useValue: config }] };
}

Allow unknown elements

legacy

For web components used inside Angular templates.

@NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA] })

Use a module inside a standalone app

bootstrapApplication(App, {
  providers: [importProvidersFrom(LegacyModule)],
});

Use a standalone component inside a module

v20+

Standalone components go in imports, never declarations.

@NgModule({ imports: [UserCard] })

What Angular is

Angular is a TypeScript framework for building web applications, maintained by Google and released on a six-month cadence. It ships with routing, forms, an HTTP client, a testing setup and a build system in the box, which is the main thing that separates it from the lighter alternatives that leave those decisions to you.

The version this sheet targets is Angular 22, released in June 2026. If you learned Angular before version 17, a lot of what you know still works, but the recommended way to write almost everything has changed.

Three shifts define modern Angular:

  • Standalone components. Components declare their own template dependencies through an imports array. NgModules still work, but nothing new needs them.
  • Signals. State is held in signal objects that track their own readers, so Angular knows precisely which views to update.
  • Zoneless change detection. With signals doing the tracking, zone.js is no longer required. New Angular 22 projects leave it out by default.

Signals, in one pass

A signal is a value with a getter. You read it by calling it, and any template or computation that reads it is registered as a dependency.

count = signal(0);

// read
this.count();

// write
this.count.set(5);
this.count.update(c => c + 1);

There are three pieces to learn, and most Angular code uses only these:

  • signal() holds state you write to.
  • computed() derives state from other signals. It is lazy and memoized, so it recalculates only when a dependency actually changed and something reads the result.
  • effect() runs a side effect when its dependencies change. Use it for logging, storage and imperative DOM work, not for deriving values.

The rule that saves the most debugging time: if you are tempted to set one signal inside an effect, you almost certainly want computed() or linkedSignal() instead. Angular’s own signals guide and its linkedSignal page document both in full.

Why signals replaced the old model

Before signals, Angular relied on zone.js to patch every asynchronous browser API and then re-check the component tree after anything happened. It worked, but it checked far more than necessary and it made performance hard to reason about. Signals invert that: the framework is told exactly what changed and which views read it.


Component syntax you will write daily

A modern component is a class with a decorator, no module in sight. The complete metadata surface is documented in Angular’s components guide.

@Component({
  selector: 'app-user-card',
  imports: [DatePipe],
  template: `
    <h2>{{ user().name }}</h2>
    <p>Joined {{ user().joined | date }}</p>
  `,
})
export class UserCard {
  user = input.required<User>();
  removed = output<string>();
}

Note what is absent: no standalone: true (it is the default since v19), no changeDetection line (OnPush is the default in v22), and no constructor.

Inputs, outputs and two-way binding

Signal-based input() and output() replaced the @Input() and @Output() decorators. Inputs read like any other signal, which means they compose directly into computed() without an ngOnChanges hook.

For two-way binding, model() creates a writable signal that also emits a matching change event, so a parent can write [(checked)]="isOn" against a child that declares checked = model(false).


Template control flow

Angular 17 introduced block syntax that replaced the structural directives. It is built into the compiler, so there is nothing to import. The full grammar, including @switch and the contextual variables inside @for, is in the control flow guide.

@if (user(); as u) {
  <p>{{ u.name }}</p>
} @else {
  <a routerLink="/login">Sign in</a>
}

@for (item of items(); track item.id) {
  <li>{{ item.label }}</li>
} @empty {
  <li>Nothing here yet.</li>
}

The track expression is required, and it matters more than it looks. Angular uses it to decide which DOM nodes to keep between renders. A stable unique identifier keeps the list cheap; tracking by index on a reordering list forces Angular to rebuild rows that did not change.

Deferred loading

@defer is the piece with no equivalent in the old directive set. It splits a chunk of template into its own lazy bundle and gives you declarative triggers for when to fetch it.

@defer (on viewport; prefetch on idle) {
  <app-comments />
} @placeholder (minimum 500ms) {
  <div class="skeleton"></div>
} @loading (after 100ms) {
  <app-spinner />
} @error {
  <p>Could not load comments.</p>
}

Triggers include on idle, on viewport, on interaction, on hover, on timer, on immediate and when with any expression. Add hydrate on ... and the same block controls incremental hydration on a server-rendered page. Angular documents every trigger in the @defer reference, and the server-side half in Incremental Hydration.


Data loading with resources

The resource API became stable in Angular 22 and is now the shortest path from an async source to loading, error and value state.

userId = signal(1);

user = httpResource<User>(() => `/api/users/${this.userId()}`);

// template
@if (user.isLoading()) {
  <app-spinner />
} @else if (user.hasValue()) {
  <h1>{{ user.value().name }}</h1>
}

Three flavours cover most needs. resource() takes a promise loader, rxResource() takes an observable stream, and httpResource() wraps HttpClient. All three re-run when a signal read inside their parameters changes, and all three hand you an abortSignal so the previous request is cancelled rather than raced. The loader contract and the full status machine are described in Async reactivity with resources.

HttpClient has not gone anywhere. Use it directly when your API integration needs interceptors, upload progress, or full control over the response. Use a resource when what you want is state bound to a template.


Forms: two stacks, one recommendation

Angular now ships two form systems, and the choice is mostly about when your project started.

ConcernSignal FormsReactive Forms
package@angular/forms/signals@angular/forms
source of trutha signal holding your modela FormGroup tree you build
validationschema function next to the modelvalidators attached per control
arraysplain arrays plus applyEachFormArray API
statesignalsobservables and getters
statusstable in v22stable, fully supported

Signal Forms invert the usual setup. Instead of describing a form and then syncing it with your data, you start from the data and let the form structure follow.

model = signal({ email: '', password: '' });

loginForm = form(this.model, (path) => {
  required(path.email, { message: 'Email is required' });
  email(path.email, { message: 'Enter a valid email' });
  minLength(path.password, 8);
});

Reactive Forms are not deprecated and large applications should not rush a rewrite. Start new forms on the signal API, keep existing ones where they are. Angular publishes both stacks side by side: the Signal Forms overview and the wider forms guide.


Routing

Routes are plain objects, registered with provideRouter() at bootstrap. Lazy loading is a function that returns a dynamic import, and guards are ordinary functions that can call inject().

export const routes: Routes = [
  { path: '', component: Home, title: 'Home' },
  {
    path: 'admin',
    loadComponent: () => import('./admin').then(m => m.Admin),
    canMatch: [adminGuard],
  },
  { path: '**', component: NotFound },
];

Two features are worth turning on early. withComponentInputBinding() maps route params, query params and resolved data straight onto component inputs, which removes most ActivatedRoute boilerplate. And canMatch beats canActivate for protected lazy routes, because it runs before the chunk downloads. Both are covered in Angular’s routing guide.


Dependency injection

Angular's dependency injection resolves services through a hierarchical injector tree. A service marked providedIn: 'root' is a tree-shakable singleton: if nothing injects it, it never reaches the bundle.

The inject() function has largely replaced constructor parameters. It works in field initializers, reads better with inheritance, and lets guards, resolvers and interceptors be plain functions instead of classes.

export class UserList {
  private users = inject(UserService);
  private route = inject(ActivatedRoute);
}

Providing a service on a component instead of at the root gives every instance of that component its own copy, which is the standard way to scope wizard state, panel state or a per-dialog store. The full injector hierarchy and every provider recipe are documented in Angular’s dependency injection guide.


Performance: what actually moves the numbers

Angular publishes its own performance guide; this is the short list of levers that pay off most often in real projects.

  • Track by a stable key. The single most common cause of sluggish lists is a track expression that changes when the data reorders.
  • Defer below the fold. @defer (on viewport) keeps charts, comment threads and editors out of the initial bundle.
  • Go zoneless. Dropping zone.js removes a polyfill and stops the framework from checking views that nothing touched.
  • Prioritize the LCP image. NgOptimizedImage with priority preloads the largest image and warns when dimensions are missing.
  • Keep function calls out of templates. Anything written as {{ compute() }} may run on every check. Wrap it in a computed() instead.
  • Set budgets. A build that fails on bundle size catches regressions that code review will not.

Version timeline

VersionReleasedWhat it introduced
v16May 2023Signals in developer preview, required inputs, standalone APIs maturing
v17Nov 2023Built-in control flow, @defer, new build system, angular.dev
v18May 2024Zoneless in experimental, @let, ng-content fallbacks
v19Nov 2024Standalone by default, linkedSignal, resource preview, incremental hydration
v20May 2025Signal APIs stable, native animate.enter and animate.leave, httpResource
v21Nov 2025Zoneless stable, Vitest, Signal Forms experimental, Angular Aria preview
v22Jun 2026Signal Forms and resources stable, OnPush by default, selectorless components, Angular Aria stable

Angular's release cycle gives each major 18 months of support: six months active, then twelve months of long-term support with security and critical fixes only. That policy is published as Angular versioning and releases, and the change-by-change detail lives in the Angular change log on GitHub.


Migrating an older codebase

Angular ships codemods that do most of the code refactoring for you, so this step is largely mechanical. Run them one at a time and make a Git commit between each, so your unit tests can tell you exactly what moved.

ng update @angular/core @angular/cli

ng generate @angular/core:standalone
ng generate @angular/core:control-flow
ng generate @angular/core:inject
ng generate @angular/core:signal-inputs
ng generate @angular/core:signal-queries
ng generate @angular/core:output-migration
ng generate @angular/core:cleanup-unused-imports

Upgrade one major at a time rather than jumping several versions. The update tool only knows how to migrate between adjacent releases, and skipping versions means skipping the schematics that would have done the work for you. The interactive Angular Update Guide prints the exact steps for any from-version to to-version pair, and Keeping up-to-date explains the tooling behind ng update.

What not to rush

Reactive Forms, NgModules in stable feature areas and working RxJS pipelines are all still supported. Angular has been careful about removals, and rewriting working code for no user-facing benefit does not pay down technical debt, it manufactures risk. Convert when you are already touching the code.


Common mistakes

  • Forgetting to call the signal. {{ count }} renders the function itself. It needs {{ count() }}.
  • Setting signals inside effects. This creates feedback loops that are hard to trace. Derive with computed().
  • Subscribing without cleanup. Use takeUntilDestroyed() or the async pipe rather than storing subscriptions by hand.
  • Missing imports on standalone components. If a directive or pipe silently does nothing, it is almost always absent from imports.
  • Wildcard route placed too early. Routes match top to bottom, so ** must be last.
  • mergeMap where switchMap belongs. For search-as-you-type, mergeMap lets stale responses arrive after fresh ones. The RxJS operator guide has the marble diagrams that make the difference obvious.
  • Touching the DOM in ngOnInit under SSR. Use afterNextRender(), which never runs on the server.

Reading the version badges

Every snippet carries the earliest Angular version it works in. A badge reading v19+ means the API landed in Angular 19 and still works today. A badge reading core means it predates the signals era and works in every supported release.

The filter in the header answers the question you actually have. Pick the version you are running and the sheet hides anything you cannot use yet. Snippets marked legacy still work but are no longer the recommended approach, and the toggle next to the version filter removes them.

A handful of APIs are marked experimental. Angular ships those outside its usual semantic versioning promise, so they can change in a patch release. In Angular 22 that applies to debounced(), injectAsync and selectorless components.


Accessibility with Angular Aria

Angular Aria became stable in v22. It is a set of headless directives that implement the WAI-ARIA patterns most teams get subtly wrong: keyboard interaction, focus management, and the correct roles and states.

Headless means it ships no styles at all. You own the markup, the CSS and the UI/UX design, and the directives handle behaviour. Because they set the ARIA attributes for you, those attributes double as your styling hooks:

[aria-selected='true'] { background: #e8f0fe; }
[aria-expanded='true'] .icon { transform: rotate(180deg); }

It is a separate install, npm install @angular/aria, with entry points per pattern: accordion, combobox, grid, listbox, menu, tabs, toolbar and tree. Angular documents the directives in its Angular Aria guide and the wider rules in accessibility best practices; the patterns themselves come from the W3C ARIA Authoring Practices Guide.


Internationalization

Angular's built-in i18n is compile-time. You mark text with the i18n attribute, extract it to a translation file, and your build pipeline emits one bundle per locale. There is no runtime language switch, which is why the bundles are small and there is no flash of untranslated content.

<h1 i18n="site header|Greeting after login@@homeWelcome">Welcome back</h1>

The value is meaning|description@@id, and all three parts are optional. Setting an explicit id is worth the keystrokes: without one, Angular generates an id from the source text, so fixing a typo in English silently orphans every translation of that string.

The workflow is ng extract-i18n, then ng build --localize once the translated files are listed in angular.json. If you need to switch language at runtime without a page load, you want a library such as Transloco or ngx-translate instead. The extraction and build steps are documented end to end in Angular’s internationalization guide.


Security defaults

Angular escapes interpolated values, so {{ userInput }} can never inject markup. Binding to [innerHTML] runs the value through the sanitizer, which strips script tags and inline event handlers.

The escape hatch is DomSanitizer. Treat every call to bypassSecurityTrustHtml or its siblings as something that needs a second pair of eyes: the method name is a promise you are making to the framework, and it is only safe on values you constructed yourself.

Two things Angular does not do for you: it does not validate anything on your back end, and it does not set your Content Security Policy. For CSP, ngCspNonce lets Angular tag the styles it injects with your per-request nonce. Angular lists every sanitization context in its security guide, and MDN documents the header itself in the Content-Security-Policy reference.


Keyboard and usage notes

Press / anywhere on the page to focus the search box and Escape to clear it. Search is ranked, so a match in a snippet's description outranks a match buried in its code, and it tolerates a single typo when nothing matches exactly. With results on screen, Arrow Up and Arrow Down step through them and Enter copies the highlighted one.

The topic rail is a tab list: once one topic has focus, the arrow keys move between them and Home and End jump to the ends.

Every view has its own link. Opening a topic or running a search updates the address bar, so you can bookmark #ngcs=signals or send someone #ngcs=search&q=defer&v=19 and they will land on exactly what you were looking at, filter included. Browser back and forward work as expected.

Every snippet has a copy button. Snippets with a Why button carry a note explaining a gotcha, a default that changed, or the reason one approach beats another. The page prints cleanly too: the chrome and controls drop away, all topics expand, and the notes stay visible.


Official documentation for every topic on this sheet

A cheat sheet is a shortcut, not a substitute. Every claim on this page is written against Angular’s own documentation for the release it names, and each of the 23 topics in the reference above maps to a page on angular.dev. When you need the full API surface rather than the one-line version, go straight to the source.

Topic on this sheetOfficial reference
CLI & SetupAngular CLI reference · Installation
ComponentsComponents guide
Templates & BindingTemplates overview · Binding
Control FlowControl flow · @defer
SignalsSignals overview · linkedSignal · effect
Async & ResourcesAsync reactivity with resources
DirectivesDirectives guide
PipesPipes
Dependency InjectionDependency injection
RoutingRouting overview · Define routes
Signal FormsSignal Forms overview · Validation · Comparison with other form systems
Reactive & Template FormsForms overview · Reactive forms · Template-driven forms
HttpClientHTTP client guide
RxJS in AngularRxJS operators · RxJS interop
TestingTesting guide · Testing HttpClient
Errors & DebuggingUnhandled errors · Angular DevTools
SecuritySecurity best practices
SSR & PerformanceServer-side rendering · Hydration · Incremental hydration · Performance
Internationalizationi18n guide
Angular AriaAngular Aria · Accessibility · W3C ARIA APG
AnimationsAnimations guide
Elements & PWAService workers & PWAs · MDN: custom elements
NgModulesNgModules overview
Versions & migrationVersioning and releases · Update guide · API reference

Two more worth bookmarking: the Angular style guide, which settles most naming and file-structure arguments, and the TypeScript handbook, since a surprising share of “Angular” errors are really type errors.


How this cheat sheet is kept current

Last updated . The sheet targets Angular 22 and is re-checked after every major release, which lands roughly every six months.

What that check involves:

  • Version badges are set from the release in which each API first shipped, cross-checked against the Angular change log rather than from memory.
  • API names and signatures are read from the Angular API reference for the version in question, not from blog posts.
  • Stability claims (“stable in v22”, “experimental”, “legacy”) follow Angular’s published versioning and deprecation policy.
  • The current release number is confirmed against @angular/core on npm and the release write-ups on the Angular blog.
  • Anything on the roadmap but not yet shipped is left off the sheet until it appears in a stable release; Angular publishes what is coming on its public roadmap.

Written and maintained by Bogdan Sandu at TMS Outsource. If a snippet has drifted from the docs, or a version badge looks wrong, the fastest fix is to check it against the linked page above and tell us - corrections get applied to the sheet, and the date at the top of this section moves with them.