The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·23

Angular

Angular as a complete framework: components, templates and control flow, directives and pipes, dependency injection (compared with Spring), services, routing with guards and lazy loading, reactive forms, RxJS and signals, change detection with and without Zone.js, SSR and hydration, HTTP interceptors, testing and the CLI.

38 topics · ~35 min read · 27-question quiz
Updated Suggest a correction

Start here: your first Angular app

What Angular is

Angular is a complete, opinionated framework from Google for building web applications in TypeScript. Where React is a UI library you combine with other libraries, Angular ships the whole kit: components and templates, dependency injection, a router, forms, an HTTP client, testing utilities, server-side rendering and a CLI that generates and builds everything in one consistent style. That consistency is why it's popular for large enterprise applications built by many teams, including a lot of Java shops, which find its classes, decorators and dependency injection familiar from Spring. It releases a major version every six months; Angular 22 (June 2026) is current, with each major supported for 18 months.

Components: a class plus a template

An Angular component is a TypeScript class with a @Component decorator that gives it an HTML tag name (selector) and a template:

TypeScript
@Component({
  selector: "app-item",
  template: `
    <li [class.done]="item().done">
      <span>{{ item().text }}</span>
      <button type="button" (click)="toggle.emit(item().id)">{{ item().done ? "Undo" : "Done" }}</button>
      <button type="button" (click)="remove.emit(item().id)">Remove</button>
    </li>`,
})
class ItemComponent {
  item = input.required<Item>();         // data flows down…
  toggle = output<string>();             // …events flow up
  remove = output<string>();
}

Wherever another template writes <app-item>, Angular creates an instance of this class and renders its template there. The class holds the data and logic; the template describes the view. In a CLI project, components usually live in their own files (item.component.ts with an item.component.html template and a .css file whose styles are scoped to the component).

Template syntax in five forms

Angular templates are HTML with a small set of binding syntaxes. Each kind of bracket means a direction:

Syntax Direction Example Meaning
{{ expr }} class → view {{ item().text }} insert text (escaped, so user data can't inject HTML)
[prop]="expr" class → view [disabled]="!valid()", [class.done]="…" set a DOM property, class, style or component input
(event)="statement" view → class (click)="save()" run code when an event fires
[(ngModel)]="field" both ways [(ngModel)]="text" keep a form field and a property in sync (the "banana in a box")
@if, @for, @switch, @defer control flow @for (item of items(); track item.id) { … } conditionals, loops (with a required track key), lazy blocks

The Angular compiler checks templates against your TypeScript types. Pass a string where the child expects an Item, or misspell a property, and the build fails:

Text
src/list.ts:36:22 - error TS2322: Type 'string' is not assignable to type 'Item'.
src/list.ts:41:40 - error TS2551: Property 'itmes' does not exist on type 'AppComponent'. Did you mean 'items'?

Signals: Angular's reactive state

Modern Angular keeps state in signals (chapter 21's fine-grained reactivity): values that know who reads them.

TypeScript
const items = signal<Item[]>([]);                                  // a writable signal
items();                                                           // read it by calling it
items.set([...]);                                                  // replace the value
items.update(list => [...list, newItem]);                          // compute the new value from the old
const left = computed(() => items().filter(i => !i.done).length);  // derived; recomputed only when items changes
effect(() => localStorage.setItem("items", JSON.stringify(items())));   // side effect; re-runs when items changes

When a signal a template reads changes, Angular updates just the affected views. As in React, you replace values instead of mutating them: the lab shows exactly how a mutated array leaves the screen inconsistent.

The shopping list in Angular

TypeScript
@Component({
  selector: "app-root",
  imports: [ItemComponent, FormsModule],
  template: `
    <main>
      <h1>Shopping list</h1>
      <form (ngSubmit)="add()">
        <label for="item">New item</label>
        <input id="item" name="item" [(ngModel)]="text" />
        <button>Add</button>
      </form>
      <ul>
        @for (item of items(); track item.id) {
          <app-item [item]="item" (toggle)="toggle($event)" (remove)="remove($event)" />
        } @empty {
          <li>Nothing yet</li>
        }
      </ul>
      <p>{{ left() }} item{{ left() === 1 ? "" : "s" }} left</p>
    </main>`,
})
class AppComponent {
  items = signal<Item[]>(JSON.parse(localStorage.getItem("items") ?? "[]"));
  text = "";
  left = computed(() => this.items().filter(i => !i.done).length);      // derived, recomputed only when items changes

  constructor() {
    effect(() => localStorage.setItem("items", JSON.stringify(this.items())));   // re-runs whenever items changes
  }
  add() {
    if (!this.text.trim()) return;
    this.items.update(list => [...list, { id: crypto.randomUUID(), text: this.text, done: false }]);
    this.text = "";
  }
  toggle(id: string) { this.items.update(list => list.map(i => (i.id === id ? { ...i, done: !i.done } : i))); }
  remove(id: string) { this.items.update(list => list.filter(i => i.id !== id)); }
}

bootstrapApplication(AppComponent);

Driven in Chromium (the same steps as chapters 17 and 22):

Text
empty list shows: Nothing yet
[x] Rice (5 kg), [ ] Toor dal, [ ] <img src=x onerror=alert(1)> | 2 items left
[x] Rice (5 kg), [ ] <img src=x onerror=alert(1)> | 1 item left
saved: Rice (5 kg) ✓, <img src=x onerror=alert(1)>

Compare it with chapter 22's React version: the ideas are the same (state, derived values, child components with inputs and outputs, keyed loops, an effect for saving), expressed as a class with a separate template instead of a function returning JSX. computed replaces React's "compute during render", effect replaces useEffect, and track item.id is React's key.

Services and dependency injection

Data and logic that several components share (the cart, the logged-in user, API calls) go in a service: a class Angular creates and hands to whoever asks for it. This is dependency injection (DI), the same idea as Spring's beans:

TypeScript
@Injectable({ providedIn: "root" })            // one shared instance for the whole app
export class CartService {
  private readonly lines = signal<{ name: string; price: number }[]>([]);
  readonly count = computed(() => this.lines().length);
  readonly total = computed(() => this.lines().reduce((s, l) => s + l.price, 0));
  add(name: string, price: number) { this.lines.update(ls => [...ls, { name, price }]); }
}

@Component({ selector: "app-cart-badge", template: `<span>🛒 {{ cart.count() }} · ₹{{ cart.total() }}</span>` })
class CartBadgeComponent { protected cart = inject(CartService); }

@Component({ selector: "app-menu", template: `…<button (click)="cart.add(d.name, d.price)">Add {{ d.name }}</button>…` })
class MenuComponent { protected cart = inject(CartService); }
Text
after Add Dosa : 🛒 1 · ₹90
after Add Idli : 🛒 2 · ₹140
after Add Dosa : 🛒 3 · ₹230

The menu and the header badge never reference each other; both inject the same CartService, and the badge updates because it reads the service's signals. In tests you can provide a fake CartService instead, without changing either component.

What else is in the box

  • Router: maps URLs to components, with lazy loading (loadComponent: () => import(...)), guards and resolvers.
  • Forms: Signal Forms (stable since Angular 22) and reactive forms, with validation.
  • HttpClient: typed HTTP calls with interceptors (for adding auth headers, handling errors).
  • RxJS: a library of composable streams (Observables) for event-heavy logic like search-as-you-type; signals and RxJS interoperate (toSignal, toObservable).
  • SSR and hydration, @defer blocks for lazy-loading parts of a page, and the CLI (ng generate component, ng build, ng test).

How deep to go in Angular

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Read components, templates, bindings, signals and services
L2 Build apps with standalone components, signals, DI, router, forms and HttpClient
L3 Explain the compiler (AOT, Ivy), change detection (OnPush default, zoneless scheduling), the DI hierarchy, signals vs RxJS, hydration and @defer
L4 Diagnose stale views, injector errors, change-detection and signal bugs, subscription leaks and slow bundles
L5 Design module boundaries, state services, lazy routes, and SSR/hydration strategy for large apps
L6 Run Angular at scale: six-monthly upgrades with ng update, monorepos, design systems, performance budgets

Angular's shape

A batteries-included framework

Angular (Google; "Angular 2+", distinct from the original AngularJS) is a complete framework: components, a template compiler, dependency injection, a router, forms, an HTTP client, i18n, animations, testing tools, SSR, and a CLI with code generators and an esbuild/Vite-based build. React is a library you assemble a stack around (chapter 24). Angular gives you one opinionated way to do each thing. That makes it popular for large enterprise teams: consistent structure across projects, TypeScript throughout, and strong conventions. Angular's architecture will feel familiar to a Spring developer: DI, services, decorators/annotations, interceptors, guards and modules.

Angular releases a major version every six months, with automated migrations (ng update). Recent versions changed a lot: standalone components (no NgModules required), signals, new control flow syntax (@if, @for), deferrable views (@defer), zoneless change detection, incremental hydration, and esbuild-based builds. Older tutorials built on NgModules and Zone.js describe a style that's now legacy.

Components and templates

Components

A component is a TypeScript class with a @Component decorator that links it to a template and styles:

TypeScript
import { Component, input, output, computed, signal } from "@angular/core";
import { CurrencyPipe } from "@angular/common";

@Component({
  selector: "app-cart-item",                  // used as <app-cart-item> in templates
  imports: [CurrencyPipe],                     // standalone: declare what the template uses
  template: `
    <div class="item" [class.out-of-stock]="!item().inStock">
      <h3>{{ item().name }}</h3>
      <p>{{ total() | currency: 'INR' }}</p>
      <button type="button" (click)="remove.emit(item().id)" [attr.aria-label]="'Remove ' + item().name">×</button>
      <input type="number" min="1" [value]="qty()" (input)="qty.set(+$any($event.target).value)" />
    </div>
  `,
  styleUrl: "./cart-item.component.css",       // encapsulated to this component by default
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CartItemComponent {
  item = input.required<Item>();               // signal input (replaces @Input())
  remove = output<string>();                   // output (replaces @Output() EventEmitter)
  qty = signal(1);                             // local reactive state
  total = computed(() => this.item().price * this.qty());   // derived state
}

Since Angular 19, components are standalone by default: each declares its own template dependencies in imports, and there's no NgModule needed. Applications start with bootstrapApplication(AppComponent, appConfig).

Lifecycle hooks are interface methods: ngOnInit (after the first inputs are set: initialisation that needs inputs), ngOnChanges (input changes, for decorator inputs), ngAfterViewInit (the view and child views are ready, so DOM queries work), and ngOnDestroy (cleanup). Newer alternatives: DestroyRef.onDestroy(), effect() for reacting to signals, and afterNextRender/afterEveryRender for DOM work that must run in the browser (they're SSR-safe).

Templates and binding

Angular templates are HTML extended with bindings. The template compiler turns them into efficient instructions at build time (AOT compilation, with the Ivy engine):

Syntax Direction Example
{{ expr }} Component → view (text) {{ user().name }}
[prop]="expr" Property binding [disabled]="busy()", [src]="url"
[attr.x] / [class.x] / [style.x] Attribute, class, style binding [attr.aria-expanded]="open()", [style.width.px]="w"
(event)="handler($event)" View → component (click)="save()", (keydown.enter)="submit()"
[(ngModel)]="x" / [(value)] Two-way (property + event) Banana-in-a-box syntax; model() signals support it
#ref Template reference variable <input #q> <button (click)="search(q.value)">
@let Template local variable @let total = subtotal() + tax();

Built-in control flow (Angular 17+, replacing the old *ngIf/*ngFor structural directives):

HTML
@if (orders().length > 0) {
  <ul>
    @for (order of orders(); track order.id) {      <!-- track is REQUIRED: the key, as in React -->
      <li>{{ order.id }} — {{ order.total | currency }}</li>
    } @empty {
      <li>No orders yet.</li>
    }
  </ul>
} @else if (loading()) {
  <app-spinner />
} @else {
  <p>Nothing here.</p>
}

@switch (status()) {
  @case ("shipped") { <app-badge tone="success">Shipped</app-badge> }
  @default { <app-badge>{{ status() }}</app-badge> }
}

@defer (on viewport; prefetch on idle) {           <!-- deferrable views: lazy-load this chunk -->
  <app-reviews [productId]="id()" />
} @placeholder { <div class="skeleton"></div> } @loading (minimum 300ms) { <app-spinner /> } @error { <p>Couldn't load reviews.</p> }

@for requires track, which plays the role of React's key: a stable identity for each item. @defer code-splits part of a template and loads it on a trigger (viewport, idle, interaction, hover, timer, or a condition). It's one of the easiest ways to cut initial bundle size.

Directives

Directives add behaviour to existing elements. There are two kinds (components are a third kind, directives with a template):

  • Attribute directives change appearance or behaviour, like Spring AOP aspects applied to DOM elements:
TypeScript
@Directive({ selector: "[appAutofocus]" })
export class AutofocusDirective {
  private el = inject(ElementRef<HTMLElement>);
  constructor() { afterNextRender(() => this.el.nativeElement.focus()); }
}
// <input appAutofocus>
  • Structural directives change DOM structure by adding and removing templates (the * syntax). The old *ngIf/*ngFor are structural directives. Custom ones (*appHasRole="'admin'") use TemplateRef and ViewContainerRef.

Built-ins include NgClass, NgStyle, NgTemplateOutlet and NgComponentOutlet. Host directives (hostDirectives) compose directive behaviour into components without inheritance, which is composition over inheritance again (Vol. 1 ch. 2). Angular CDK supplies many behaviour directives: cdkTrapFocus, cdkDrag, cdkConnectedOverlay and cdkVirtualFor.

Pipes

Pipes transform values for display in templates: {{ value | pipeName: arg1 : arg2 }}.

Pipe Example
date {{ createdAt | date: 'mediumDate' }} (locale-aware)
currency, number, percent {{ total | currency: 'INR' : 'symbol' : '1.0-0' }}
async {{ user$ | async }}: subscribes to an Observable or Promise and unsubscribes automatically
json, slice, keyvalue, uppercase, titlecase, i18nPlural
TypeScript
@Pipe({ name: "initials" })                        // pure by default: re-runs only when the input reference changes
export class InitialsPipe implements PipeTransform {
  transform(name: string): string {
    return name.split(/\s+/).map(p => p[0]?.toUpperCase() ?? "").join("").slice(0, 2);
  }
}

Pipes are pure by default, so they're memoised on their inputs, which makes them cheaper than calling a method in the template. A template method call like {{ format(x) }} re-runs on every change-detection pass. Signals and computed() reduce the need for both.

Dependency injection and services

Dependency injection

Angular has a full dependency injection container, conceptually the same as Spring's IoC container (Vol. 3), but hierarchical and closely tied to the component tree:

TypeScript
@Injectable({ providedIn: "root" })          // an application-wide singleton, tree-shakable (like a Spring @Service singleton)
export class OrderService {
  private http = inject(HttpClient);         // inject() function: the modern style (constructor injection also works)
  private config = inject(APP_CONFIG);       // an InjectionToken for non-class values

  list(status?: string) {
    return this.http.get<Order[]>(`${this.config.apiUrl}/orders`, { params: status ? { status } : {} });
  }
}

export const APP_CONFIG = new InjectionToken<{ apiUrl: string }>("APP_CONFIG");

// app.config.ts — the composition root (like a Spring @Configuration class)
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withInterceptors([authInterceptor, errorInterceptor])),   // fetch-based by default since v22
    provideZonelessChangeDetection(),
    { provide: APP_CONFIG, useValue: { apiUrl: "/api" } },
    { provide: Logger, useClass: environment.production ? RemoteLogger : ConsoleLogger },   // swap implementations
  ],
};

Provider recipes: useClass, useValue, useFactory (with dependencies), useExisting (an alias), and multi: true (collect several providers into an array, which is how interceptors and initialisers are registered, like Spring injecting a List<Interceptor>).

The DI hierarchy

Angular's injectors form a hierarchy. Lookups go up the tree until a provider is found:

platform injector root (providedIn: 'root') lazy route: /admin providers lazy route: /shop providers AdminTable componentelement injector: providers: [...] Cart componentviewProviders / providers resolution walks UP ↑
Angular's injector hierarchy. A token is resolved from the requesting component's element injector upward, then through environment injectors to the root and platform.
  • Environment injectors: the root injector (providedIn: "root" and the providers in appConfig), plus one per lazy-loaded route that has providers. Services provided there are scoped to that feature.
  • Element injectors: providers or viewProviders in a @Component or @Directive. That gives one instance per component instance, shared with its children. It's useful for component-scoped state, such as a wizard's state service shared by its steps (like Spring's prototype or request scopes).
  • Resolution modifiers: inject(X, { optional: true }), { self: true }, { skipSelf: true } and { host: true } control where the lookup starts and stops.

Compared with Spring: both use constructor and field injection, singletons by default, qualifiers (InjectionToken versus @Qualifier), factories (useFactory versus @Bean methods) and multi-binding. Angular's distinctive feature is the tree-shaped hierarchy that mirrors the UI. Spring's contexts form a hierarchy too, but scopes are mostly tied to time (request, session) rather than position in a tree.

Services

Services hold logic and state that don't belong in a component: data access, business rules, caching, shared state, logging and auth. Components should stay thin (presentation and wiring) and delegate to services, the same separation as Spring's controller → service → repository layers. A simple signal-based store service:

TypeScript
@Injectable({ providedIn: "root" })
export class CartStore {
  private readonly _items = signal<CartItem[]>([]);
  readonly items = this._items.asReadonly();                       // expose read-only
  readonly count = computed(() => this._items().reduce((n, i) => n + i.qty, 0));
  readonly total = computed(() => this._items().reduce((s, i) => s + i.qty * i.price, 0));

  add(item: Product) {
    this._items.update(items => {
      const existing = items.find(i => i.id === item.id);
      return existing
        ? items.map(i => (i.id === item.id ? { ...i, qty: i.qty + 1 } : i))
        : [...items, { ...item, qty: 1 }];
    });
  }
}

For larger apps, NgRx SignalStore (or classic NgRx Store, a Redux implementation) adds structured state management (chapter 25).

Routing

The router

TypeScript
// app.routes.ts
export const routes: Routes = [
  { path: "", component: HomeComponent, title: "Home" },
  { path: "products/:id", component: ProductComponent, resolve: { product: productResolver } },
  {
    path: "admin",
    canMatch: [roleGuard("admin")],                          // the route doesn't even match for non-admins
    loadChildren: () => import("./admin/admin.routes").then(m => m.ADMIN_ROUTES),   // lazy-loaded feature
  },
  { path: "settings", loadComponent: () => import("./settings/settings.component").then(m => m.SettingsComponent) },
  { path: "**", component: NotFoundComponent },
];
HTML
<nav>
  <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }" ariaCurrentWhenActive="page">Home</a>
  <a [routerLink]="['/products', product.id]" [queryParams]="{ tab: 'reviews' }">Reviews</a>
</nav>
<router-outlet />

With withComponentInputBinding(), route params, query params and resolver data bind straight to component input()s (id = input.required<string>()). The router supports nested routes (child <router-outlet>s), named outlets, redirects, title (it updates document.title), scroll restoration (withInMemoryScrolling), view transitions (withViewTransitions()), and preloading strategies.

Guards and resolvers

Guards are functions that decide whether navigation may proceed. They're like Spring Security's access rules, but for UI routes:

TypeScript
export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isLoggedIn() ? true : router.createUrlTree(["/login"], { queryParams: { returnUrl: state.url } });
};

export const roleGuard = (role: string): CanMatchFn => () => inject(AuthService).hasRole(role);

export const unsavedChangesGuard: CanDeactivateFn<{ hasUnsavedChanges(): boolean }> =
  (component) => !component.hasUnsavedChanges() || confirm("Discard unsaved changes?");
Guard Runs Use
canMatch Before the route is even matched (and before lazy code loads) Role-based feature access; alternative routes per role
canActivate / canActivateChild Before activating Authentication
canDeactivate Before leaving Unsaved-changes prompts
resolve Before activating, fetching data Pre-loading required data (prefer loading in the component with signals or resources for better perceived performance)

Client-side guards are UX, not security. The JavaScript is public, and anyone can call your API directly. Every API endpoint must enforce authorisation on the server (Vol. 3, Spring Security).

Lazy loading

loadChildren and loadComponent with dynamic import() create separate bundles that load only when the route is first visited. Combined with @defer blocks inside templates, they keep the initial JavaScript small (chapter 27). Preloading strategies (withPreloading(PreloadAllModules), or a custom strategy for likely routes, such as on hover or for routes flagged data: { preload: true }) fetch lazy bundles in the background after the app is idle.

Forms

Angular has two forms systems, plus a new signal-based one in development.

Reactive forms

Reactive forms define the form model in TypeScript, explicitly and with types:

TypeScript
@Component({
  selector: "app-signup",
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <label for="email">Email</label>
      <input id="email" formControlName="email" type="email" autocomplete="email"
             [attr.aria-invalid]="form.controls.email.invalid && form.controls.email.touched"
             aria-describedby="email-err" />
      @if (form.controls.email.touched && form.controls.email.errors?.["email"]) {
        <p id="email-err" class="error">Enter a valid email address.</p>
      }
      <div formGroupName="password">
        <input formControlName="value" type="password" autocomplete="new-password" />
        <input formControlName="confirm" type="password" autocomplete="new-password" />
      </div>
      @if (form.controls.password.errors?.["mismatch"]) { <p class="error">Passwords don't match.</p> }
      <button type="submit" [disabled]="form.pending">Create account</button>
    </form>
  `,
})
export class SignupComponent {
  private fb = inject(NonNullableFormBuilder);
  form = this.fb.group({
    email: ["", [Validators.required, Validators.email], [uniqueEmailValidator()]],   // sync + async validators
    password: this.fb.group(
      { value: ["", [Validators.required, Validators.minLength(12)]], confirm: [""] },
      { validators: [matchValidator("value", "confirm")] },                            // cross-field validator
    ),
  });

  submit() {
    if (this.form.invalid) { this.form.markAllAsTouched(); return; }
    const value = this.form.getRawValue();   // { email: string; password: { value: string; confirm: string } }
  }
}

The model is a tree of FormControl, FormGroup and FormArray (for dynamic lists), and it's typed since Angular 14. Each control exposes value, status, errors, touched/dirty, valueChanges/statusChanges (Observables), and setValue/patchValue/reset.

Validators

Validators are functions from a control to ValidationErrors | null:

TypeScript
export function matchValidator(a: string, b: string): ValidatorFn {
  return (group) => group.get(a)?.value === group.get(b)?.value ? null : { mismatch: true };
}

export function uniqueEmailValidator(): AsyncValidatorFn {
  const api = inject(UserApi);
  return (control) => timer(300).pipe(                      // debounce
    switchMap(() => api.emailExists(control.value)),         // cancels the previous check
    map(exists => (exists ? { emailTaken: true } : null)),
    catchError(() => of(null)),
  );
}

Built-ins: required, requiredTrue, email, min, max, minLength, maxLength, pattern, nullValidator. Template-driven forms (ngModel) are simpler for small forms, but harder to test and to make dynamic. Signal Forms (experimental in Angular 21, stable since Angular 22, June 2026) define forms from a signal model with schema-based validation, and are now the recommended approach for new forms.

As always: client validation is UX, and the server must validate again (chapter 13). With Spring, the server's Bean Validation errors (as RFC 9457 Problem Details) can be mapped back onto controls with control.setErrors({ server: message }).

Reactivity: RxJS and signals

RxJS and Observables

RxJS implements Observables: lazy, push-based streams of values over time that can be composed with operators. It's the reactive-streams model you'll meet again as Project Reactor's Flux/Mono in Spring WebFlux (Vol. 3), Kotlin Flow, and Java's Flow API. Angular's HTTP client, router events, form valueChanges and many libraries expose Observables.

TypeScript
// Typeahead search: a classic RxJS pipeline
readonly results$ = this.searchControl.valueChanges.pipe(
  map(q => q.trim()),
  debounceTime(300),                 // wait for a pause in typing
  distinctUntilChanged(),            // skip if unchanged
  filter(q => q.length >= 2),
  switchMap(q =>                     // CANCEL the previous request when a new query arrives (fixes the race in ch. 15)
    this.api.search(q).pipe(catchError(() => of([] as Product[]))),
  ),
  shareReplay({ bufferSize: 1, refCount: true }),   // share one subscription among template consumers
);

The flattening operators are the key concepts (Vol. 1 ch. 8's concurrency policies, for streams):

Operator When a new outer value arrives while an inner one is running Use
switchMap Cancel the previous inner one Search, route-param loading: latest wins
mergeMap Run concurrently (optionally limited) Independent parallel requests
concatMap Queue: one at a time, in order Ordered writes
exhaustMap Ignore new values until the current one completes Prevent double-submit on login or save

Subscriptions must end. An Observable subscribed in a component and never unsubscribed leaks (and keeps calling back after the component is destroyed). Use the async pipe (it unsubscribes automatically), takeUntilDestroyed(), or convert to signals with toSignal(). HTTP Observables complete after one response, but valueChanges, interval and router events don't.

Signals

Signals (Angular 16+, now the core of Angular's reactivity) are reactive values that track their dependencies automatically:

TypeScript
const count = signal(0);                          // writable signal
const doubled = computed(() => count() * 2);      // derived, lazy, memoised; recomputes only when count changes
effect(() => console.log("count is", count()));   // side effect that re-runs when its dependencies change

count.set(5); count.update(c => c + 1);
doubled();                                        // 12, read by calling

// Resources: async data as signals (stabilising in recent versions)
userId = input.required<string>();
user = httpResource<User>(() => `/api/users/${this.userId()}`);   // re-fetches when userId changes; .value(), .isLoading(), .error()

// Linked signals: writable state that resets when a source changes
selected = linkedSignal(() => this.options()[0]);

Signals are fine-grained: Angular knows exactly which templates and computeds read which signals, so it can update only the affected views rather than checking the whole component tree. The same signals idea powers Solid, Preact Signals, Vue's refs, Svelte 5's runes and Qwik, and a TC39 proposal aims to standardise signals in JavaScript itself (chapter 25).

Observables versus signals

Signals Observables (RxJS)
Model A value that changes; always has a current value A stream of events over time
Read Synchronous: count() Subscribe (async)
Push or pull Push notification, pull value (lazy computeds) Push
Best for UI state, derived state, template bindings Events and async coordination: debounce, cancellation, retry, combining streams, WebSockets
Cleanup Automatic (dependency tracking) Manual (unsubscribe, async pipe, takeUntilDestroyed)
Glitch-free Yes: computeds see consistent state Can emit intermediate combinations (combineLatest)

They're complementary: use signals for state and RxJS for complex async event flows, and convert at the boundary with toSignal(obs$) and toObservable(sig). Angular's direction is signal-first, with RxJS optional.

Change detection

How change detection works

Change detection (CD) is how Angular keeps the DOM in sync with component state. In each CD pass, Angular walks the component tree from the root, evaluates every template binding, compares it with the previous value, and updates the DOM where it changed.

Default strategy: every component is checked on every pass. That's simple but O(size of the app) per event.

OnPush: a component is checked only when (1) one of its inputs changes by reference, (2) an event fires inside it, (3) an async pipe or signal it reads emits, or (4) it's explicitly marked (ChangeDetectorRef.markForCheck()). Otherwise Angular skips the component and its subtree. OnPush plus immutable data is the standard performance practice, and since Angular 22 it is the default strategy for every component; the old behaviour is now called Eager (ChangeDetectionStrategy.Eager), and the v22 migration adds it to existing components that didn't specify a strategy.

Zone.js and zoneless

How does Angular know when to run change detection? Historically, through Zone.js: a library that monkey-patches every async browser API (setTimeout, promises, addEventListener, XHR and fetch) so that Angular is notified after any async task finishes, and then runs CD for the whole app. It's convenient (things "just update"), but it has costs: about 30 KB of extra JavaScript, CD runs after every event even when nothing changed, it's hard to debug, it's incompatible with native async/await (code must be downlevelled to generators), and third-party scripts trigger app-wide CD.

Zoneless change detection (stable in Angular 20.2, and the default for new apps in Angular 21) removes Zone.js. Angular schedules CD only when it's told something changed:

  • A signal read in a template changes (the main mechanism).
  • A template event listener runs.
  • An async pipe emits, markForCheck() is called, or inputs are set via setInput.
TypeScript
bootstrapApplication(AppComponent, {
  providers: [provideZonelessChangeDetection()],   // and remove "zone.js" from polyfills
});

Going zoneless means: use signals (or the async pipe, or markForCheck) for all state that templates read, and stop relying on "mutate a field in a setTimeout and the view magically updates". With signals plus OnPush, Angular can update just the affected views, which is the direction the framework has taken: fine-grained reactivity with change detection that's scheduled, not global.

Server rendering and HTTP

SSR and hybrid rendering

Angular's SSR (ng new --ssr, or ng add @angular/ssr) renders routes on a Node (or edge) server, and hydrates them in the browser (chapter 22's concepts):

  • Per-route render modes (hybrid rendering): RenderMode.Prerender (SSG at build time), RenderMode.Server (SSR per request), or RenderMode.Client (CSR only), configured in app.routes.server.ts.
  • Full-app hydration reuses the server DOM instead of re-rendering it. Event replay captures clicks that happen before hydration finishes and replays them afterwards.
  • Incremental hydration (stable since Angular 20, on by default since Angular 22, which deprecated withIncrementalHydration()): combined with @defer (hydrate on viewport | interaction | idle), parts of a server-rendered page stay dehydrated (static HTML, with no JavaScript downloaded) until a trigger fires. It's Angular's version of islands and resumability (chapter 24).
  • Use afterNextRender/isPlatformBrowser for browser-only code, and TransferState/HttpClient transfer caching to avoid fetching the same data again on the client.

HttpClient and interceptors

HttpClient returns typed Observables with JSON by default. Since Angular 22 it uses the Fetch API by default (withFetch() is deprecated; withXhr() restores XMLHttpRequest, which is still needed for upload progress events, since fetch can't report them), and reportProgress is split into reportUploadProgress and reportDownloadProgress:

TypeScript
this.http.get<Order[]>("/api/orders", { params: { page: 2 } })
  .pipe(retry({ count: 2, delay: (_, n) => timer(2 ** n * 200) }), timeout(8000))
  .subscribe({ next: setOrders, error: showError });

Interceptors are middleware for every request and response. They're the same concept as Spring's ClientHttpRequestInterceptor and HandlerInterceptor, and servlet filters (Vol. 3):

TypeScript
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).accessToken();
  const authed = token && req.url.startsWith("/api") ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
  return next(authed);
};

export const errorInterceptor: HttpInterceptorFn = (req, next) =>
  next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      if (err.status === 401) inject(Router).navigate(["/login"]);
      inject(Toaster).error(err.error?.detail ?? "Something went wrong");   // RFC 9457 problem detail from Spring
      return throwError(() => err);
    }),
  );

export const correlationInterceptor: HttpInterceptorFn = (req, next) =>
  next(req.clone({ setHeaders: { "X-Request-Id": crypto.randomUUID() } }));   // trace across services (ch. 32)

Interceptors run in the order they're provided for requests, and in reverse for responses. Requests are immutable, so use clone(). Typical interceptors: auth headers, refresh-token handling, base URLs, correlation IDs, loading indicators, caching, error mapping and retries.

Tooling

Testing

Angular includes testing utilities built on DI:

TypeScript
describe("CartStore", () => {
  it("adds and counts items", () => {
    TestBed.configureTestingModule({});
    const store = TestBed.inject(CartStore);
    store.add({ id: "p1", name: "Socks", price: 200 });
    store.add({ id: "p1", name: "Socks", price: 200 });
    expect(store.count()).toBe(2);
    expect(store.total()).toBe(400);
  });
});

describe("OrderListComponent", () => {
  it("renders orders from the service", async () => {
    await TestBed.configureTestingModule({
      imports: [OrderListComponent],
      providers: [provideHttpClient(), provideHttpClientTesting()],
    }).compileComponents();
    const fixture = TestBed.createComponent(OrderListComponent);
    const http = TestBed.inject(HttpTestingController);
    fixture.detectChanges();
    http.expectOne("/api/orders").flush([{ id: "o1", total: 899 }]);   // fake the backend
    await fixture.whenStable();
    expect(fixture.nativeElement.textContent).toContain("o1");
    http.verify();
  });
});

The test runner has historically been Karma + Jasmine, which is now deprecated. Current Angular uses Vitest (the default in new projects since Angular 21) or Jest. Angular Testing Library gives user-centric queries (screen.getByRole), and Playwright or Cypress handle E2E (chapter 26). Component harnesses from Angular CDK and Material give stable test APIs for complex components.

The CLI and the build

The Angular CLI (ng) scaffolds, builds, serves, tests and updates:

Terminal
$ ng new shop --ssr --style=css           # standalone, signals, esbuild by default
$ ng generate component orders/order-list # also: service, directive, pipe, guard, interceptor, resolver
$ ng serve                                # Vite-based dev server with HMR
$ ng build                                # production: AOT compile, esbuild bundling, tree-shaking, minification, budgets
$ ng test                                 # unit tests
$ ng update @angular/core @angular/cli    # automated migrations (schematics) between major versions
$ ng generate @angular/core:signal-input-migration   # e.g. migrate @Input() to input()

The build uses the @angular/build:application builder (esbuild for production bundles, and Vite for the dev server). It compiles templates ahead of time (AOT): template errors become build errors, and the compiler isn't shipped to the browser. It enforces bundle budgets (angular.json budgets: warn or fail when the initial bundle exceeds limits), so set them. Nx (chapter 30) is popular for large Angular monorepos.

Lab: Angular's reactivity, measured

The components below were compiled ahead of time with Angular 22's compiler (ngc, the compiler the CLI wraps), bundled with esbuild, and run in Chromium 153. Angular 22 is zoneless and OnPush by default, so these experiments show the framework's current behaviour, not the Zone.js-era one most tutorials describe. The RxJS experiment ran in Node 22 with RxJS 7.8.

Experiment 1: signals, computed values and a mutation bug

A cart held in a signal, a computed total that logs each time it recalculates, and an effect that logs what it saw. The test reads the screen and the log after each action:

TypeScript
cart = signal([{ name: "Dosa", price: 90, qty: 1 }]);
discount = signal(0);
plainField = 0;
total = computed(() => { log("total computed"); return this.cart().reduce((s, d) => s + d.price * d.qty, 0) - this.discount(); });
constructor() { effect(() => log(`effect saw ${this.cart().length} line(s)`)); }
mutateInPlace() { this.cart().push({ name: "Idli", price: 50, qty: 2 }); }
addProperly()   { this.cart.update(c => [...c, { name: "Vada", price: 40, qty: 1 }]); }
Text
initial render                           | Total: ₹90  | Dosa × 1                      | log: effect saw 1 line(s); total computed
read total() three more times            | Total: ₹90  | Dosa × 1                      | log: -
cart().push(...) (mutation)              | Total: ₹90  | Dosa × 1, Idli × 2            | log: -
click a button bound to a plain field    | Total: ₹90  | Dosa × 1, Idli × 2            | log: -
cart.update(c => [...c, x])              | Total: ₹230 | Dosa × 1, Idli × 2, Vada × 1  | log: effect saw 3 line(s); total computed
discount.set(20) then set(30), no event  | Total: ₹200 | Dosa × 1, Idli × 2, Vada × 1  | log: total computed

Line by line:

  • computed is lazy and cached. Reading total() three more times didn't recompute it; it only recalculates when a signal it read has changed since.
  • The mutation produced an inconsistent screen. After push, the click event caused the component's template to re-run, and @for found the new Idli line in the (same) array, but the total stayed ₹90 and the effect never ran, because the cart signal was never told anything changed. The page showed two items and the price of one. This class of bug (half the UI updated) is worse than nothing updating, and it's why signals and React state both require new values.
  • A plain class field still updates on events: the clicked button's text changed to 1, because an event inside an OnPush component marks it for checking. But a plain field changed from a setTimeout or a promise would not update in a zoneless app; that's the main migration work from older Angular.
  • update() fixed everything at once: the list, the total (90 + 100 + 40 = 230) and the effect.
  • Signal writes are batched and need no event. Two set calls from outside any event caused one recomputation, and the DOM updated by itself: Angular's zoneless scheduler runs change detection after signal writes, then applies the changes on the next frame. (One consequence for tests: read the DOM after await fixture.whenStable(), not immediately after the write.)

Experiment 2: four ways to combine async requests in RxJS

The search-as-you-type problem from chapter 15 (the user types "d", "do", "dos", "dosa" 30 ms apart; the fake server answers in 300, 50, 120 and 80 ms), expressed as an RxJS stream with each "flattening" operator:

TypeScript
input.pipe(switchMap(q => search(q))).subscribe(show);    // or mergeMap, concatMap, exhaustMap
Text
mergeMap (all, any order)      do@83ms → dosa@173ms → dos@183ms → d@303ms
concatMap (all, in order)      d@301ms → do@354ms → dos@474ms → dosa@555ms
switchMap (cancel previous)    dosa@173ms
exhaustMap (ignore while busy) d@302ms
debounce 100 ms + switchMap    dosa@274ms

These four operators are the main reason to learn RxJS: each encodes a concurrency policy in one word. mergeMap reproduces chapter 15's bug (the final result is "d"); concatMap is correct but slow; switchMap unsubscribes from the previous inner request (and Angular's HttpClient aborts the HTTP request when that happens), so only the latest query's result arrives; exhaustMap ignores new triggers while one is running, which is exactly right for a "Place order" button pressed twice. Adding debounceTime(100) sent just one request instead of four. Signals model state; RxJS models events over time; Angular's interop (toSignal, toObservable, rxResource) lets each do its job.

Experiment 3: type-checked templates

With strictTemplates (the default since Angular 22), the compiler type-checks every binding against the component classes. Two deliberate mistakes in the shopping list:

HTML
<app-item [item]="text" …/>                     <!-- text is a string; the input wants an Item -->
<p>{{ left().toFixed() }} item{{ itmes().length }}</p>
Text
src/list.ts:36:22 - error TS2322: Type 'string' is not assignable to type 'Item'.
src/list.ts:41:40 - error TS2551: Property 'itmes' does not exist on type 'AppComponent'. Did you mean 'items'?

The template is compiled into TypeScript code (a type-check block) and checked with the same compiler as your classes, so templates get the same safety and editor support as code. One more detail from compiling these experiments: Angular 22 requires TypeScript 6 and refused to compile until the configuration set rootDir explicitly, one of TypeScript 6's new defaults (chapter 16).

Try it yourself

  1. In experiment 1, change a plain field inside setTimeout and watch it fail to render. Fix it three ways: a signal, ChangeDetectorRef.markForCheck(), and (to see the old behaviour) provideZoneChangeDetection().
  2. Rebuild experiment 2's search as an Angular component using toSignal(searchTerms.pipe(debounceTime(150), switchMap(q => http.get(...)))), then again with httpResource(). Which reads better?
  3. Provide CartService in a component's providers array instead of root. What happens to the badge, and why (the DI hierarchy)?
  4. Run ng update on a project two major versions behind, and read every migration it applies.

Revision sheet: Angular

Key ideas

  • Standalone components (class + decorator + template), imports per component; templates compiled ahead of time (Ivy) into instructions and type-checked (strictTemplates, default since v22).
  • Bindings: {{ }}, [prop], (event), [(model)]; built-in control flow @if/@for (with track)/@switch/@defer; pipes for display transforms.
  • Signals: signal, computed (lazy, cached), effect, linkedSignal; signal-based input(), output(), model(), queries; resource/httpResource for async data (stable since v22).
  • Change detection: OnPush by default since v22 (old behaviour renamed Eager); zoneless by default since v21: views update after signal writes, events, async pipe emissions or markForCheck().
  • Dependency injection: inject(), providedIn: "root", environment and element injector hierarchy, InjectionTokens, providers for testing.
  • Router: lazy loadComponent/loadChildren, functional guards and resolvers, route-level providers, input binding from route params.
  • Forms: Signal Forms (stable since v22) and reactive forms; validators; typed forms.
  • HTTP: HttpClient (fetch-based by default since v22), interceptors, httpResource.
  • RxJS for event streams: switchMap, mergeMap, concatMap, exhaustMap, debounceTime; takeUntilDestroyed; toSignal/toObservable.
  • SSR: hydration, event replay, incremental hydration (default since v22) with @defer (hydrate on …).

Numbers to remember

  • A major release every 6 months; each supported 18 months (6 active + 12 LTS).
  • Angular 22: TypeScript 6 and Node 22+ required.

Pitfalls

  • Mutating arrays and objects held in signals (inconsistent views, as in the lab).
  • Plain fields changed outside events in zoneless apps; reading the DOM before whenStable() in tests.
  • effect used to derive state (use computed or linkedSignal).
  • Manual subscribe without takeUntilDestroyed (leaks); nested subscribes instead of flattening operators.
  • Providing a service in a component when you meant a singleton (or vice versa).
  • Huge shared modules or barrel files defeating lazy loading.

Glossary

  • Decorator: an annotation (@Component, @Injectable) that attaches metadata to a class.
  • Injector: the container that creates and supplies service instances.
  • Zoneless: change detection scheduled by signals and events instead of Zone.js patching async APIs.
  • Type-check block: generated TypeScript the compiler uses to check a template.
  • Flattening operator: an RxJS operator that maps each value to an inner Observable and merges the results under a concurrency policy.
  • @defer block: a template section whose code is lazy-loaded on a trigger (viewport, interaction, idle).