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
New application
Angular 22 generates standalone, zoneless, OnPush projects by default.
ng new my-appSkip prompts, accept defaults
ng new my-app --defaultsPick a stylesheet format
Options: css, scss, sass, less.
ng new my-app --style=scssWith server-side rendering
Adds @angular/ssr, a server entry point and hydration wiring.
ng new my-app --ssrWithout SSR
ng new my-app --no-ssrKeep Zone.js instead of zoneless
New v22 projects are zoneless unless you opt out.
ng new my-app --no-zonelessNgModule based project
Only for teams still on the module architecture.
ng new my-app --no-standaloneChoose a package manager
Also accepts npm, yarn, bun, cnpm.
ng new my-app --package-manager=pnpmSet the selector prefix
Components become <acme-user-card>.
ng new my-app --prefix=acmeCreate without installing deps
ng new my-app --skip-installEmpty workspace, no app
Useful for a monorepo of libraries.
ng new my-workspace --create-application=falseServe, build, watch
Dev server
Alias: ng s. Hot module replacement is on by default.
ng serveCustom port and auto-open
ng serve --port 4300 --openExpose on the local network
Handy for testing on a phone.
ng serve --host 0.0.0.0Serve a named configuration
ng serve --configuration=productionDisable hot module replacement
ng serve --no-hmrProduction build
Defaults to the production configuration.
ng buildDevelopment build
ng build --configuration developmentRebuild on change
ng build --watchEmit a bundle stats file
Feed it to a bundle analyzer.
ng build --stats-jsonDeploy under a sub-path
ng build --base-href /app/Control file hashing
Values: none, media, bundles, all.
ng build --output-hashing=allSource maps in a prod build
ng build --source-mapGenerate code
Component
Short form: ng g c user-card.
ng generate component user-cardComponent in a folder, flat
ng g c shared/user-card --flatInline template and styles
ng g c badge --inline-template --inline-styleComponent without a spec file
ng g c badge --skip-testsService
Short form: ng g s data.
ng g service dataAttribute directive
ng g directive highlightPipe
ng g pipe truncateFunctional route guard
ng g guard auth --functionalHTTP interceptor
ng g interceptor authRoute resolver
ng g resolver userInterface, enum, class
ng g interface user
ng g enum status
ng g class user-modelEnvironment files
Creates src/environments and wires the file replacement.
ng g environmentsExtra app or library in the workspace
ng g application admin
ng g library ui-kitNgModule with routing
ng g module admin --routingUpdate, add, inspect
Show what can be updated
ng updateUpdate the framework and CLI together
Core and CLI majors must match.
ng update @angular/core @angular/cliJump to a specific major
ng update @angular/core@22 @angular/cli@22Add a package with its schematic
Runs the library's install-time setup.
ng add @angular/materialAdd SSR to an existing app
ng add @angular/ssrTurn the app into a PWA
ng add @angular/pwaPrint versions and environment
Short form: ng v.
ng versionRun unit tests once, headless
Vitest is the default runner in v22.
ng test --watch=false --browsers=ChromeHeadlessTests with coverage
ng test --coverageLint
Requires ng add @angular/eslint first.
ng lintManage the build cache
ng cache info
ng cache clean
ng cache disableOpt out of usage analytics
ng analytics offRead or set a workspace config value
ng config cli.packageManager pnpmAutomated migrations
Convert to standalone components
Run it three times: convert, prune imports, bootstrap.
ng generate @angular/core:standaloneRewrite *ngIf and *ngFor as @if and @for
ng generate @angular/core:control-flowConvert @Input() to signal input()
ng generate @angular/core:signal-inputsConvert @Output() to output()
ng generate @angular/core:output-migrationConvert @ViewChild and @ContentChild to signal queries
ng generate @angular/core:signal-queriesMove constructor params to inject()
ng generate @angular/core:injectDrop unused standalone imports
ng generate @angular/core:cleanup-unused-importsUse self-closing tags
ng generate @angular/core:self-closing-tagComponents
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
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 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
Optional input with a default
Reads as a signal: this.size().
size = input('medium');
// template: <app-chip size="large" />Required input
The compiler errors if a parent forgets to bind it.
user = input.required<User>();Aliased input
value = input(0, { alias: 'count' });Transform an incoming value
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
name = input('', { transform: (v: string) => v.trim().toLowerCase() });Output and emit
saved = output<User>();
save() {
this.saved.emit(this.user());
}
// template: <app-form (saved)="onSaved($event)" />Output with no payload
closed = output();
this.closed.emit();Two-way binding with model()
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
value = model.required<string>();Output from an observable
import { outputFromObservable } from '@angular/core/rxjs-interop';
search = outputFromObservable(this.query$);Decorator inputs and outputs
Basic input
Still supported, but signal inputs are the recommended path.
@Input() user!: User;Required and aliased input
@Input({ required: true, alias: 'userId' }) id!: string;Input with transform
@Input({ transform: booleanAttribute }) disabled = false;Setter input
@Input()
set user(value: User) {
this._user = value;
}Output with EventEmitter
@Output() saved = new EventEmitter<User>();
this.saved.emit(user);Manual two-way binding
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
With signal inputs, use computed() or effect() instead.
ngOnChanges(changes: SimpleChanges) {
if (changes['user'] && !changes['user'].firstChange) {
this.reload();
}
}Lifecycle hooks
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
private destroyRef = inject(DestroyRef);
constructor() {
this.destroyRef.onDestroy(() => clearInterval(this.id));
}Run once after the next render
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
Named afterRender before v20.
import { afterEveryRender } from '@angular/core';
afterEveryRender(() => this.syncScroll());Reactive render effect
import { afterRenderEffect } from '@angular/core';
afterRenderEffect(() => {
this.el.nativeElement.style.height = this.height() + 'px';
});View and content queries
Single view child
input = viewChild<ElementRef>('box');
// this.input()?.nativeElementRequired view child
No optional chaining needed at the call site.
canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas');Many view children
rows = viewChildren(RowComponent);
// this.rows() is a readonly arrayQuery a component instance
picker = viewChild(DatePicker);Read a specific token
vcr = viewChild('host', { read: ViewContainerRef });Projected content queries
tabs = contentChildren(Tab);
header = contentChild(TabHeader);Decorator view child
static: true resolves before ngOnInit but only for non-conditional elements.
@ViewChild('box') box!: ElementRef;
@ViewChild('box', { static: true }) early!: ElementRef;Decorator content children
@ContentChildren(Tab, { descendants: true }) tabs!: QueryList<Tab>;Content projection
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
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
Bind a host property
@HostBinding('class.active') isActive = false;
@HostBinding('attr.aria-expanded') expanded = 'false';Listen on the host
@HostListener('click', ['$event'])
onClick(e: MouseEvent) { }Listen on window or document
@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
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
Basic listener
<button (click)="save()">Save</button>The event object
<input (input)="onInput($event)" />
// onInput(e: Event) { (e.target as HTMLInputElement).value }Key modifiers
<input (keydown.enter)="submit()" (keydown.escape)="cancel()" />Key combinations
<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
<app-form (saved)="onSaved($event)" (cancelled)="close()" />Statement chaining
<button (click)="first(); second()">Both</button>Two-way binding and refs
Two-way with ngModel
Requires FormsModule in imports.
<input [(ngModel)]="name" />Two-way with a model input
Works with model() on the child.
<app-toggle [(checked)]="isOn" />Expanded two-way form
<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
@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
@let profile = profile$ | async;
@if (profile) {
<h2>{{ profile.name }}</h2>
}Expression helpers
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
@if
@if (user()) {
<p>Welcome back.</p>
}@if / @else if / @else
@if (status() === 'loading') {
<app-spinner />
} @else if (status() === 'error') {
<app-error />
} @else {
<app-content />
}Alias the condition result
Avoids calling the signal repeatedly.
@if (user(); as u) {
<p>{{ u.name }}</p>
}@for with a track expression
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
@for (todo of todos(); track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li class="muted">Nothing to do.</li>
}Loop context variables
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
@for (tag of tags(); track $index) {
<span>{{ tag }}</span>
}@switch
Comparison is strict equality, and @default is optional.
@switch (role()) {
@case ('admin') { <app-admin /> }
@case ('editor') { <app-editor /> }
@default { <app-viewer /> }
}Deferred loading
Lazy load a chunk of template
Defaults to the on idle trigger.
@defer {
<app-heavy-chart />
}Full block with all sub-blocks
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
@defer (on interaction) { <app-editor /> }
@defer (on hover) { <app-preview /> }Trigger from another element
<button #more>Show more</button>
@defer (on interaction(more)) {
<app-details />
}Timer and immediate triggers
@defer (on timer(2s)) { <app-promo /> }
@defer (on immediate) { <app-banner /> }Condition based trigger
when evaluates once and does not re-trigger after it fires.
@defer (when isVisible()) {
<app-panel />
}Combine triggers
Whichever fires first wins.
@defer (on viewport; on timer(5s)) {
<app-widget />
}Prefetch ahead of time
@defer (on interaction; prefetch on idle) {
<app-editor />
}Incremental hydration
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
@defer (hydrate never) {
<app-legal-footer />
}Structural directives
*ngIf
Needs CommonModule or NgIf in imports.
<p *ngIf="user">Welcome</p>*ngIf with else
<p *ngIf="user; else guest">Welcome</p>
<ng-template #guest><p>Sign in</p></ng-template>*ngIf with then and else
<ng-container *ngIf="ok; then good; else bad" />*ngIf as
<p *ngIf="user$ | async as user">{{ user.name }}</p>*ngFor with trackBy
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
// trackById(index: number, item: Item) { return item.id; }*ngFor context variables
<li *ngFor="let x of list; index as i; first as isFirst; last as isLast">{{ i }}</li>ngSwitch
<div [ngSwitch]="role">
<app-admin *ngSwitchCase="'admin'" />
<app-viewer *ngSwitchDefault />
</div>ngClass and ngStyle
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
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
Calling the signal in a template registers a dependency.
count = signal(0);
// read
this.count();Replace the value
this.count.set(10);Derive from the previous value
this.count.update(c => c + 1);Typed signal with an explicit type
user = signal<User | null>(null);Custom equality
Skips notifying dependents when the comparison returns true.
user = signal(initial, { equal: (a, b) => a.id === b.id });Expose a read-only view
Standard pattern for signal-based stores.
private _items = signal<Item[]>([]);
readonly items = this._items.asReadonly();Update an array immutably
this.items.update(list => [...list, newItem]);
this.items.update(list => list.filter(i => i.id !== id));Update an object immutably
this.form.update(f => ({ ...f, email: value }));Derived state
Computed signal
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
filtered = computed(() => this.items().filter(i => i.active));
count = computed(() => this.filtered().length);Computed from an input
greeting = computed(() => `Hello, ${this.name()}`);Writable derived state
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
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
The effect re-runs for userId only.
import { untracked } from '@angular/core';
effect(() => {
const id = this.userId();
const cfg = untracked(() => this.config());
});Effects
Basic effect
Must run in an injection context, or be given an injector.
constructor() {
effect(() => console.log('count is', this.count()));
}Effect with cleanup
effect((onCleanup) => {
const id = setInterval(() => this.tick(), 1000);
onCleanup(() => clearInterval(id));
});Effect created outside the constructor
private injector = inject(Injector);
start() {
effect(() => this.sync(this.value()), { injector: this.injector });
}Manually destroy an effect
const ref = effect(() => this.log());
ref.destroy();Persist state to storage
Do not set other signals here; prefer computed or linkedSignal for derived state.
effect(() => localStorage.setItem('theme', this.theme()));RxJS interop
Observable to signal
import { toSignal } from '@angular/core/rxjs-interop';
user = toSignal(this.userService.user$, { initialValue: null });Require a synchronous first value
Works with BehaviorSubject or startWith.
state = toSignal(this.store.state$, { requireSync: true });Signal to observable
import { toObservable } from '@angular/core/rxjs-interop';
query$ = toObservable(this.query);Auto-unsubscribe
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
constructor() {
this.ws.messages$
.pipe(takeUntilDestroyed())
.subscribe(m => this.push(m));
}Outside an injection context
private destroyRef = inject(DestroyRef);
load() {
this.api.poll()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
}Debounce a signal without RxJS
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
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
Zoneless change detection
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
Promise based resource
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
@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
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
this.user.reload();Locally override the value
The value signal is writable, which suits optimistic updates.
this.user.value.set(editedUser);Available state signals
resource.value() // T | undefined
resource.status() // idle | loading | reloading | resolved | error | local
resource.isLoading() // boolean
resource.hasValue() // boolean narrowing guard
resource.error() // unknownObservable based resource
import { rxResource } from '@angular/core/rxjs-interop';
user = rxResource({
params: () => this.userId(),
stream: id => this.http.get<User>(`/api/users/${id}`),
});HTTP resource
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
results = httpResource<Result[]>(() => ({
url: '/api/search',
params: { q: this.query() },
headers: { 'X-Scope': 'public' },
}));Validate the response
Any parser works, for example a Zod schema.
user = httpResource(() => `/api/users/${this.id()}`, {
parse: UserSchema.parse,
});Skip loading until ready
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
Attribute directive
@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
@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
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
<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
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, 2026Currency
{{ 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
@for (entry of settings | keyvalue; track entry.key) {
<li>{{ entry.key }}: {{ entry.value }}</li>
}Async
Subscribes and unsubscribes for you.
{{ user$ | async }}
@if (user$ | async; as user) { {{ user.name }} }Custom pipes
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
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
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
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
Return a promise or observable and Angular waits for it.
provideAppInitializer(() => {
const config = inject(ConfigService);
return config.load();
})APP_INITIALIZER
{
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
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
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
Bind route params straight to inputs
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
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
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.stateReact to router events
this.router.events
.pipe(filter(e => e instanceof NavigationEnd))
.subscribe(() => window.scrollTo(0, 0));Guards and resolvers
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
{ path: 'admin', canActivateChild: [authGuard], children: [...] }Router features
Scroll restoration and anchor scrolling
provideRouter(routes,
withInMemoryScrolling({
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
}))View transitions
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
provideRouter(routes, withComponentInputBinding())Log navigation events
provideRouter(routes, withDebugTracing())Custom error handling
provideRouter(routes, withNavigationErrorHandler(e => inject(Logger).error(e)))Module based setup
RouterModule.forRoot(routes)
RouterModule.forChild(childRoutes)Signal Forms
The signal-native forms stack from @angular/forms/signals. Stable in v22.
Building a form
Model plus form
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
formField syncs the value plus required, disabled and readonly attributes.
<input [formField]="loginForm.email" />
<input type="password" [formField]="loginForm.password" />Read field state
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
Field access is fully typed all the way down.
model = signal({
name: '',
address: { city: '', zip: '' },
});
profile = form(this.model);
// profile.address.cityUpdate the model directly
The field tree reacts automatically.
this.model.update(m => ({ ...m, email: 'new@example.com' }));Validation
Built-in validators
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
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
Pass a function instead of a literal to make the bound reactive.
min(path.participants, () => this.minimumRequired(), {
message: 'Not enough participants',
});Pattern
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
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
validate(path.confirm, ({ value, valueOf }) =>
value() === valueOf(path.password)
? null
: { kind: 'match', message: 'Passwords do not match' }
);Conditional rule
required(path.promoCode, {
message: 'Promo code is required',
when: ({ valueOf }) => valueOf(path.applyDiscount),
});Validate every item in an array
applyEach(path.items, (item) => {
required(item.name, { message: 'Item name is required' });
min(item.quantity, 1);
});Apply a group of rules conditionally
applyWhen(
path,
({ valueOf }) => valueOf(path.type) === 'business',
(p) => required(p.vatNumber)
);Async validation
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
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
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
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
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
const addressSchema = schema<Address>((path) => {
required(path.city);
required(path.zip);
});
checkout = form(this.model, (path) => {
apply(path.shipping, addressSchema);
});Field behaviour and submission
Disable, hide, make read-only
disabled(path.discount, ({ valueOf }) => !valueOf(path.isMember));
readonly(path.id);
hidden(path.internalNote, () => !this.isAdmin());Debounce a field
debounce(path.search, 300);Submit
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
@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
<button [disabled]="loginForm().invalid() || loginForm().submitting()">
Save
</button>Reactive & Template Forms
The long-standing forms APIs, still fully supported.
Reactive forms
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
<div formArrayName="tags">
@for (c of tags.controls; track $index) {
<input [formControlName]="$index" />
}
</div>Values, state and validators
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.enabledEnable 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
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
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
@if (form.controls.email.touched && form.controls.email.hasError('required')) {
<p class="error">Email is required</p>
}Template-driven forms
Basic form
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-pendingCustom form controls
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
Provide the client
bootstrapApplication(App, {
providers: [provideHttpClient()],
});Use the fetch backend
Recommended, and required for streaming responses under SSR.
provideHttpClient(withFetch())Register interceptors
provideHttpClient(
withFetch(),
withInterceptors([authInterceptor, retryInterceptor]),
)Class based interceptors
provideHttpClient(withInterceptorsFromDi())Enable JSONP
provideHttpClient(withJsonpSupport())Making requests
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
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
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
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
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 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
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
Replaces the manual destroy$ subject pattern.
source$.pipe(takeUntilDestroyed())Skip early emissions
source$.pipe(skip(1))Combining
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
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
Set up and create
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
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
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
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
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
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
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
TestBed.configureTestingModule({ rethrowApplicationErrors: false });Console debugging
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
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
Produce a stats file
ng build --stats-jsonInspect it
npx esbuild-visualizer --metadata dist/my-app/stats.json
// or upload the file to a bundle analyzer of your choiceFind what pulled a package in
npm ls some-packageType-check without emitting
npx tsc --noEmit -p tsconfig.app.jsonVerbose build diagnostics
ng build --verboseSecurity
What Angular protects you from, and where you are on your own.
Sanitization
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
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
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
Add SSR to an app
Creates the server entry point and a build target.
ng add @angular/ssrEnable hydration
Reuses the server markup instead of re-rendering it.
bootstrapApplication(App, {
providers: [provideClientHydration()],
});Replay events captured before hydration
Clicks made during hydration are not lost.
provideClientHydration(withEventReplay())Incremental hydration
Enabled by default for new v22 apps.
provideClientHydration(withIncrementalHydration())
// template
@defer (hydrate on viewport) { <app-grid /> }Per-route render mode
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
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
provideServerRendering(
withRoutes(serverRoutes),
withAppShell(AppShell),
)Custom headers and status per route
{
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
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); // clientPerformance levers
Zoneless application
Removes the zone.js polyfill and only checks views tied to signals.
provideZonelessChangeDetection()OnPush everywhere
Already the default in v22.
changeDetection: ChangeDetectionStrategy.OnPushDefer below-the-fold work
@defer (on viewport) { <app-related /> }Stable track expressions
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
// 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
Add the package
ng add @angular/localizeMark 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
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
Extract messages
Produces messages.xlf. Hand that to translators, then keep messages.fr.xlf and friends alongside it.
ng extract-i18n --output-path src/localeChoose a format
ng extract-i18n --format=json
// xlf | xlf2 | xmb | json | arbDeclare 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 --localizeServe a single locale while developing
ng serve --configuration=frSet 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
Install
Not bundled with the framework, so install it before importing anything.
npm install @angular/ariaWhat it gives you
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
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
Single-select list
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
With explicit mode the user presses Space or Enter to select, rather than selection following focus.
<div ngListbox multi selectionMode="explicit">Other patterns
Accordion
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
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
The building block behind the select, multiselect and autocomplete patterns.
import {
Combobox, ComboboxInput, ComboboxPopup, ComboboxPopupContainer,
} from '@angular/aria/combobox';Available entry points
@angular/aria/accordion
@angular/aria/combobox
@angular/aria/grid
@angular/aria/listbox
@angular/aria/menu
@angular/aria/tabs
@angular/aria/toolbar
@angular/aria/treeWorks as a Signal Forms control
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
Animate an element into the DOM
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
Angular waits for the animation to end before removing the node.
<div animate.leave="fade-out">Removing</div>Bind the class name
<div [animate.enter]="enterClass()" [animate.leave]="'slide-out'"></div>Multiple classes
<div animate.enter="fade-in slide-up"></div>Bind on the host
@Component({
host: {
'[animate.enter]': "'fade-in'",
'[animate.leave]': "'fade-out'",
},
})
export class Toast {}Hand off to a JS animation library
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
Provide the animations engine
@angular/animations is deprecated as of v20.2.
providers: [provideAnimationsAsync()]Trigger, state and transition
@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
transition(':enter', [style({ opacity: 0 }), animate('200ms')]),
transition(':leave', animate('200ms', style({ opacity: 0 }))),Stagger a list
transition('* => *', [
query(':enter', stagger('60ms', animate('200ms', style({ opacity: 1 })))),
])Elements & PWA
Shipping Angular components as custom elements, and service worker basics.
Angular Elements
Add the package
ng add @angular/elementsDefine 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
Add PWA support
Adds the service worker, a manifest and icons, and wires ngsw-config.json.
ng add @angular/pwaRegister the service worker
provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000',
})Prompt the user to reload on a new version
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
Declare a module
@NgModule({
declarations: [AppComponent, UserCard],
imports: [BrowserModule, CommonModule, HttpClientModule],
providers: [UserService],
exports: [UserCard],
bootstrap: [AppComponent],
})
export class AppModule {}Bootstrap a module app
The standalone equivalent is bootstrapApplication.
platformBrowserDynamic().bootstrapModule(AppModule);Feature module with routing
@NgModule({
imports: [CommonModule, RouterModule.forChild(routes)],
})
export class AdminModule {}Shared module pattern
@NgModule({
imports: [CommonModule],
declarations: [Truncate],
exports: [CommonModule, FormsModule, Truncate],
})
export class SharedModule {}Configurable module
static forRoot(config: Config): ModuleWithProviders<CoreModule> {
return { ngModule: CoreModule, providers: [{ provide: CONFIG, useValue: config }] };
}Allow unknown elements
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
Standalone components go in imports, never declarations.
@NgModule({ imports: [UserCard] })Nothing matches. Try a single word.
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
importsarray. 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.
| Concern | Signal Forms | Reactive Forms |
|---|---|---|
| package | @angular/forms/signals | @angular/forms |
| source of truth | a signal holding your model | a FormGroup tree you build |
| validation | schema function next to the model | validators attached per control |
| arrays | plain arrays plus applyEach | FormArray API |
| state | signals | observables and getters |
| status | stable in v22 | stable, 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.
NgOptimizedImagewithprioritypreloads 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 acomputed()instead. - Set budgets. A build that fails on bundle size catches regressions that code review will not.
Version timeline
| Version | Released | What it introduced |
|---|---|---|
| v16 | May 2023 | Signals in developer preview, required inputs, standalone APIs maturing |
| v17 | Nov 2023 | Built-in control flow, @defer, new build system, angular.dev |
| v18 | May 2024 | Zoneless in experimental, @let, ng-content fallbacks |
| v19 | Nov 2024 | Standalone by default, linkedSignal, resource preview, incremental hydration |
| v20 | May 2025 | Signal APIs stable, native animate.enter and animate.leave, httpResource |
| v21 | Nov 2025 | Zoneless stable, Vitest, Signal Forms experimental, Angular Aria preview |
| v22 | Jun 2026 | Signal 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 theasyncpipe 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,
mergeMaplets stale responses arrive after fresh ones. The RxJS operator guide has the marble diagrams that make the difference obvious. - Touching the DOM in
ngOnInitunder SSR. UseafterNextRender(), 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.
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.