Workbench / Volume 2 Companion: The Web Frontend
V2·23
Angular
Companion to Volume 2, chapter 23: how Angular's templates, dependency injection and reactivity connect; new angles (an injector as a building's store rooms, signals as a kitchen's order board, zoneless change detection as a waiter who only checks tables that rang); what the chapter simplifies, measured: a sanitiser that rewrites a javascript: link and strips an onerror handler but has not touched styles since Angular 10, component styles that a strict CSP silently refuses until a nonce is added, and a build tool that is part of the framework (esbuild alone produced 144 KB gzipped, Angular's builder 44 KB, and needed a newer Node than the rest of the project); the theory behind it; how Angular's signal graph pushes "dirty" and pulls values with versions and epochs; four debugging drills, including an effect that hangs the tab with no error and an object input that makes every tick five times dearer; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 23 has three strands. Angular's shape: a batteries-included framework, components with templates, directives and pipes. Dependency injection and the platform: injectors and their hierarchy, services, the router with guards and lazy loading, reactive forms. Reactivity and tooling: RxJS, signals, change detection (OnPush and zoneless), server rendering and HttpClient, testing and the CLI.
The links worth remembering:
- Signals tell change detection what to check. A template that reads signals is a consumer in the signal graph; writing a signal marks exactly those templates for refresh, and zoneless Angular schedules a pass because of the write. Plain fields only update when something else causes a pass (the lab's Experiment 1).
- Injectors decide which instance you get.
inject()walks up from the component's injector through its parents to the application's; where you provide something decides its lifetime and who shares it. Andinject()only works while that walk is possible: during construction (drill D1). - The build is part of the framework. Templates are compiled ahead of time into instructions, and Angular's optimiser removes what those instructions don't use. Bundle size, error messages and even the Node version you need come from the build, not your code (Gaps 3, drill D1).
Explain it differently
1. An injector is a building's store rooms. Each floor has a store room; a cook asks for flour and gets it from the nearest store room that stocks it, going downstairs floor by floor until the ground-floor warehouse. Stock something on one floor and only that floor shares it; stock it in the warehouse and the whole building does.
2. Signals are a kitchen's order board. When an order changes, the board flags every station whose work depends on it ("dirty"), but nobody recooks yet. When the pass asks for a dish, the station checks whether its inputs really changed since it last cooked, and only then cooks again (Code walkthrough).
3. Zoneless change detection is a waiter who only checks tables that rang. Zone.js was a waiter who walked the whole floor after every noise in the building. Zoneless Angular checks when a signal at a table changed, an event happened at a table, or someone explicitly rang. A note left on a table without ringing (a plain field changed in a timer) goes unseen.
4. track in @for is a coat-check ticket. Angular uses it to hand each coat (DOM node and component) back to the same guest after the queue reorders. Track by $index and coats go to whoever stands in that place.
5. The sanitiser is a customs desk, not a security guard. It inspects the goods you declare at the border ([innerHTML], [href]) and confiscates the dangerous ones. Goods you wave through with a diplomatic pass (bypassSecurityTrust*) aren't inspected, and goods that never cross that border (a style, direct DOM writes) aren't its business (Gaps 1).
6. AOT compilation is a recipe turned into a station checklist. The template is written like a recipe; the compiler turns it into the exact steps for creating and updating that piece of DOM. The kitchen never needs a chef who can read recipes at service time (no runtime compiler), and steps nobody uses are left out of the checklist (Gaps 3).
7. RxJS operators are traffic rules at a junction. switchMap lets only the latest car through, concatMap queues them, mergeMap lets them all go at once, exhaustMap closes the junction until the current car has passed (the lab's Experiment 2).
8. Six-monthly majors are a kitchen's annual equipment service. Skip one and the next is harder; skip three and parts no longer fit. Upgrading is maintenance, scheduled, not a project you do when something breaks (interview Q5).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from Angular 22.2.4 built with @angular/build in production mode, Node 24.15 and Chromium (exp/23), unless stated.
1. Security: what the sanitiser does, and doesn't. The exercises' summary says Angular sanitises values bound to [innerHTML], [style] and URLs. The same hostile dish as chapter 22's companion, bound five ways and served with the build's CSP (script-src 'self'):
#t: <p id="t"><img src=x onerror=alert(1)></p>
#a: <a id="a" href="unsafe:javascript:alert(document.cookie)">Open</a>
#h: <div id="h"><b>Dosa</b><img src="x"></div>
#b: <div id="b"><b>Dosa</b><img src="x" onerror="alert(1)"></div>
#s: <div id="s"></div>
#s2: <div id="s2" style="background-image: url("/x.png");"></div>
console: ["error: Executing inline event handler violates the following Content Security Policy directive 'script-src 'self''. Either the 'unsafe-inline' keyword, a has"]
Interpolation escapes (#t). A javascript: URL is prefixed with unsafe:, so the link does nothing (#a); React 19 replaces it with a URL that throws, to the same effect. [innerHTML] keeps <b> and the image but strips onerror (#h), and in a production build it does so silently: the warning ("sanitizing HTML stripped some content") is development-only, so production logs won't tell you content was removed. bypassSecurityTrustHtml passes everything (#b); the only thing between that onerror and execution was the CSP. And styles: since Angular 10 the style context is a pass-through. The source (@angular/platform-browser, DomSanitizerImpl):
case SecurityContext.STYLE:
if (_allowSanitizationBypassAndThrow(value, "Style")) {
return _unwrapSafeValue(value);
}
return value;
#s is empty because Chromium itself refused the value: setting style.backgroundImage = 'url(javascript:alert(1))' directly gives no style either (None in the experiment). #s2 shows an ordinary URL bound to a style goes through as written, wherever it points. So the protection layers are: Angular for HTML and URLs in declared contexts; the browser for script in CSS; the CSP for everything that slips through. Code that uses ElementRef.nativeElement.innerHTML or Renderer2 with raw strings bypasses Angular entirely. The build bans bypassSecurityTrust* in its boundary check.
2. CSP: component styles are refused without a word from Angular. Angular adds each component's styles to the page as a <style> element. Under the build's style-src 'self', a component with one rule (.hot { color: rgb(200, 0, 0) }), and the same with an ngCspNonce attribute on the root element and the nonce in the policy:
?x=styled -> colour: rgb(0, 0, 0) | <style> elements: ['no nonce'] | console: ["error: Applying inline style violates the following Content Security Policy directive 'style-src 'self''. Either the 'unsafe-inline' keyword, a hash ('sha256"]
?x=styled&nonce=1 -> colour: rgb(200, 0, 0) | <style> elements: ['nonce'] | console: []
Without the nonce the text is black: the component renders, its styles don't, and the only sign is a browser console error that Angular doesn't surface. With ngCspNonce, Angular copies the nonce onto its <style> elements and the browser applies them. The nonce must be random per response, written by the server into both the header and the page (this experiment used a fixed one only to show the mechanism; a fixed nonce protects nothing). The build avoids the question: the Angular view has no component styles and uses the shared stylesheet, and the boundary check refuses styles: in angular/. Chapter 28 adds nonces properly.
3. The build tool is part of the framework. The chapter describes ng build as "AOT compile, esbuild bundling, tree-shaking, minification". The build's Angular view was first compiled with ngc and bundled with plain esbuild (the lab's method), then built with Angular's own application builder:
../../web/angular-kitchen.js 451.9kb
147633
main.js | main | 134.02 kB | 40.70 kB
45358
(The first block is esbuild's report for ngc plus esbuild; the second is the builder's table. The number under each is gzip -9 | wc -c of the file: 144 KB and 44 KB.)
The same code is 3.4 times smaller through Angular's builder. Plain esbuild can't remove most of @angular/core (339 KB of it in the first bundle, by esbuild's metafile), because Angular's code relies on build-time transformations (marking top-level calls as side-effect-free, removing decorator metadata, dropping development code) that its builder applies. The builder brings its own requirements. On this machine's Node:
Node.js version v22.22.0 detected.
The Angular CLI requires a minimum Node.js version of v22.22.3 or v24.15.0 or v26.0.0.
And Angular 22.2 needs TypeScript 6.0 ("typescript": ">=6.0 <6.1" in @angular/compiler-cli's peer dependencies), while the rest of the build's frontend is on 5.9. So the Angular view is its own package with its own toolchain, and check-js.sh takes NG_NODE to find a suitable Node. Choosing Angular is choosing its upgrade schedule for TypeScript and Node too (interview Q5).
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Angular sanitises styles." | Not since version 10; the browser rejects script in CSS, and the CSP does the rest. | Gaps 1 |
| "If the component renders, its styles work." | Under a strict CSP, component styles are refused unless they carry the page's nonce. | Gaps 2; drill D4 note |
"esbuild is what ng build does." |
Angular's builder adds optimisations that made the bundle 3.4× smaller. | Gaps 3 |
"inject() works anywhere in a component." |
Only in an injection context: construction, factories, or runInInjectionContext. |
Drill D1 |
| "An effect that writes its own input will error." | In Angular 22 it hung the tab, in production and development builds. | Drill D3 |
| "OnPush plus signals makes inputs free." | Each new object input marks its component for refresh; a tick cost 5× more. | Drill D2 |
Theoretical gaps: the ideas behind the chapter
1. Dependency injection is inversion of control with lexical scope. A component declares what it needs; the injector hierarchy decides what it gets, like a variable looked up through enclosing scopes. That's why the same token can mean different things in different subtrees, and why lifetimes follow providers, not consumers. Martin Fowler's distinction between DI and a service locator applies: inject() looks like a locator call but is resolved against the component's position, which keeps it testable.
2. Incremental DOM versus virtual DOM. Angular's compiler turns each template into creation and update instructions that work directly on the real DOM; there's no second tree to diff. React builds a virtual tree each render and diffs it. Incremental DOM uses less memory and lets unused instructions be tree-shaken; the virtual DOM lets components be ordinary functions. Both are ways of making "UI as a function of state" cheap.
3. AOT compilation is partial evaluation. A template is a program over data that isn't known yet; compiling it ahead of time evaluates everything that is known (structure, bindings, types) and leaves only the data-dependent part for run time. Type-checked templates (the lab's Experiment 3) come free from the same step.
4. Push-pull reactivity with versions. Angular's signals mark dependents dirty eagerly (push) and recompute lazily on read, checking version numbers to skip work (pull): the same algorithm as Preact Signals in chapter 21's companion, and close to the model in the TC39 signals proposal. Equality functions decide when a recomputed value counts as new (Code walkthrough).
5. Scheduling as an event loop policy. Zoneless Angular schedules a change-detection pass after a signal write or an event, racing a timer against an animation frame so the pass runs soon but in its own task. Stage 23's long-animation-frame entries show these passes as TimerHandler:setTimeout in angular-kitchen.js. Choosing when work runs (microtask, macrotask, frame) is the same trade-off as chapter 18's rendering pipeline: latency against batching.
6. Sanitisation is contextual output encoding. What makes a string safe depends on where it goes: HTML body, attribute, URL, CSS, script. Angular's security contexts (HTML, STYLE, URL, RESOURCE_URL, SCRIPT) are the OWASP output-encoding contexts, enforced by the compiler that knows each binding's destination.
Applying it
Code walkthrough
Chapter Exercises P8 uses computed, effect and linkedSignal. Underneath is a small reactive graph in @angular/core's primitives/signals. Excerpts from Angular 22.2.4, fesm2022/_effect-chunk.mjs, installed from npm.
Writing a signal: push "dirty"
function signalSetFn(node, newValue) {
if (!producerUpdatesAllowed()) {
throwInvalidWriteToSignalError(node);
}
if (!node.equal(node.value, newValue)) {
node.value = newValue;
signalValueChanged(node);
}
}
// …
function signalValueChanged(node) {
node.version++;
producerIncrementEpoch();
producerNotifyConsumers(node);
postSignalSetFn?.(node);
}
// …
function producerNotifyConsumers(node) {
if (node.consumers === undefined) {
return;
}
const prev = inNotificationPhase[0];
inNotificationPhase[0] = true;
try {
for (let link = node.consumers; link !== undefined; link = link.nextConsumer) {
const consumer = link.consumer;
if (!consumer.dirty) {
consumerMarkDirty(consumer);
}
}
} finally {
inNotificationPhase[0] = prev;
}
}
A write first asks the signal's equal function (Object.is by default), so writing an equal value does nothing. A real change bumps the signal's version and a global epoch, then walks the consumers marking each dirty, recursively; nothing is recomputed. inNotificationPhase makes reading a signal during this walk an error (producerAccessed throws), so no code can observe the graph half-marked. postSignalSetFn is the hook that tells Angular's scheduler a change detection pass is needed: that's how zoneless Angular knows when to run.
Reading a computed: pull, and only if something really changed
function consumerPollProducersForChange(node) {
for (let link = node.producers; link !== undefined; link = link.nextProducer) {
const producer = link.producer;
const seenVersion = link.lastReadVersion;
if (seenVersion !== producer.version) {
return true;
}
producerUpdateValueVersion(producer);
if (seenVersion !== producer.version) {
return true;
}
}
return false;
}
// … in COMPUTED_NODE:
producerRecomputeValue(node) {
// …
try {
newValue = node.computation();
setActiveConsumer(null);
wasEqual = oldValue !== UNSET && oldValue !== ERRORED && newValue !== ERRORED && node.equal(oldValue, newValue);
} catch (err) {
newValue = ERRORED;
node.error = err;
} finally {
consumerAfterComputation(node, prevConsumer);
}
if (wasEqual) {
node.value = oldValue;
return;
}
node.value = newValue;
node.version++;
}
Each edge remembers the version of the producer it last read. A dirty computed asks each producer, in the order it read them, whether its version moved, refreshing that producer first if needed; if none moved, it's clean without running. When it does run, its equal function decides whether the new value counts: if equal, it keeps the old value and the old version, so its own consumers see nothing new. An exception is stored as the value (ERRORED), so the error is cached like a result. The epoch lets a computed that was already checked in this epoch skip polling entirely (producerUpdateValueVersion).
Read it yourself
- A component holds
ordersin a signal.lateiscomputed(() => orders().filter(o => o.late));lateIdsis the same mapped to ids, with anequaloption comparing the arrays element by element. An effect reads each. Add an order that isn't late. Which effects run, and what does the screen show? totalis a computed that throws whenpriceis negative. Read it three times withpriceat -1, then setpriceto 45, read, and set 45 again and read. How many times does the computation run?
Debugging drills
D1. NG0203, and nothing else
The Angular display works in development. In production, a feature that loads a sanitiser in a timer callback fails, and the error report says only NG0203. The code:
constructor() { setTimeout(() => { const s = inject(DomSanitizer); /* … */ }); }
D2. Every tick costs five times more after a "tidy-up"
A colleague tidies Ticket's inputs: instead of [order], [minutes] and [late], the parent passes one [card]="c", where c comes from the cards computed, and the ticket derives order, minutes and late with computeds. Everything still works, but tb:tick (the 15-second age refresh, stage 23 measures it) goes up.
D3. The tab freezes when a component opens
A component keeps a counter in a signal and an effect that "keeps it in step": effect(() => { this.n.set(this.n() + 1); }). Opening the component freezes the tab: no error in the console, no response to clicks.
D4. Every "Accept" renders the card twice
Stage 23 added a test for the shared store: applying an order identical to one already held should publish nothing. It failed:
not ok 1 - getSnapshot returns the same object until something changes, then a new one
error: |-
Expected "actual" to be reference-equal to "expected":
+ actual - expected
{
conn: {
state: 'live'
},
+ lastChange: {
+ change: 'updated',
+ id: 'o1'
+ },
- lastChange: undefined,
On the display, accepting an order applies the command's response; a moment later the stream delivers the same order. Why does the card render twice, and what's the fix?
Career-oriented
Interview prep
Mid level
Q1. An Angular screen shows a live feed from server-sent events. Should the feed be an Observable or a signal?
How to get there. Separate the events (things that happen over time) from the state (what the screen shows now).
Q2. Your zoneless Angular page sometimes doesn't update after data arrives. What could cause it?
How to get there. List what schedules change detection in zoneless Angular, then look for updates that use none of them.
Senior level
Q3. In production, your Angular app's error reports say things like NG0203 and NG0100 with minified stack traces. Design error reporting that the team can act on.
How to get there. Think about what's stripped from production builds, what you can add back, and what context an error needs.
Q4. The kitchen display will show several kitchens on one screen, each with its own stream. How would you structure the store with Angular's dependency injection?
How to get there. Decide each object's lifetime and who shares it, then pick where to provide it.
Staff level
Q5. Your organisation has Angular and React applications in one repository. Angular now needs TypeScript 6.0 and a newer Node than the rest. Set a toolchain policy.
How to get there. Think about who upgrades what, when, and what breaks when one framework moves faster than the others.
Q6. Write a frontend security baseline that covers both React and Angular applications.
How to get there. List the places each framework protects, the places neither does, and what catches mistakes in each layer.