Workbench / Volume 2 Exercises: The Web Frontend
V2·23
Angular
Exercises for Volume 2, chapter 23: Angular's batteries-included shape, standalone components and templates, binding and control flow, directives and pipes, dependency injection and its hierarchy, services, the router with guards, resolvers and lazy loading, reactive forms and validators, RxJS and signals (and when to use each), change detection, zone.js and zoneless, SSR and hybrid rendering, HttpClient and interceptors, testing, and the CLI and build. 10 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. The measured exercises use Angular 22.2.3 compiled ahead of time with ngc (TypeScript 6), bundled with esbuild and run in Chromium 153, the setup the chapter's lab used. Every quoted output is real. A few are worth knowing before you start:
- P1: a component-level provider gave each subtree its own cart.
- P2: an impure pipe and a template method ran on every change detection, while a pure pipe ran once.
- P3: an
OnPushchild ignored a mutated input object. - P6: reading an
httpResource'svalue()while it was in an error state threw.
The lab measured signals with a mutation bug, the four RxJS flattening operators (mergeMap, concatMap, switchMap, exhaustMap) and type-checked templates. The exercises build on those.
The running example is TiffinBox's partner portal, where kitchens manage menus, orders and payouts. It's written in Angular.
Coverage map.
| Chapter component | Exercises |
|---|---|
| batteries-included framework; the CLI and the build | T1 |
| components, templates, binding, control flow | T2, P3 |
| directives | T2, P4 |
| pipes | T2, P2 |
| dependency injection, the DI hierarchy, services | T3, P1 |
| router, guards, resolvers, lazy loading | T4, P7 |
| reactive forms, validators | T5, P5 |
| RxJS and Observables | T6, P6 |
| signals (signal, computed, effect, linkedSignal, resource) | T7, P8 |
| observables versus signals | T7, P6 |
| change detection, zone.js, zoneless, OnPush | T8, P2, P3 |
| SSR and hybrid rendering | T9 |
| HttpClient and interceptors | T9, P6 |
| testing | T10, P9 |
Theory
T1. Angular's shape
- What does "batteries-included" mean for Angular (router, forms, HTTP, DI, i18n, animations, testing utilities, SSR, the CLI, a style guide), and how does that change team decisions compared with React (chapter 22)?
- Explain standalone components (the default since v19), and what replaced NgModules for organising and lazy-loading code.
- Angular's release cadence: major versions every six months, 18 months of support each,
ng updatemigrations. Why does this matter to an enterprise team, and how would you plan upgrades?
T2. Templates, directives and pipes
- Explain the binding forms: interpolation
{{ }}, property[value], event(click), two-way[(ngModel)]/ model inputs, attribute[attr.aria-label], class and style bindings, and the built-in control flow (@if,@forwithtrack,@switch,@let,@defer). - Why does
@forrequire atrackexpression, and what goes wrong withtrack $index(chapter 21's keys)? - Directives: attribute directives (change an element's behaviour or look) vs structural ones (create or remove views), host bindings and listeners, and directive composition (
hostDirectives). Pipes: what are pure and impure pipes, and P2's result (pure 0 runs, impure 5 runs, template method 5 runs across 5 unrelated change detections)?
T3. Dependency injection
- Explain Angular's DI: providers (
useClass,useValue,useFactory,useExisting),InjectionToken,inject()vs constructor injection, and why DI makes testing easy. - P1 showed the hierarchy: a
providedIn: 'root'cart service was one instance (cart#1) for the root subtree, while two<scoped-cart>components withproviders: [CartService]got their own instances (cart#2, cart#3); adding in one didn't affect the others. Explain the element and environment injectors, resolution order, and when per-component instances are what you want. - What are
providedIn: 'root'tree-shakable providers, route-level providers, and the resolution modifiersoptional,self,skipSelfandhost?
T4. Routing, guards, resolvers and lazy loading
- Design the partner portal's routes:
/login,/orders(list) and/orders/:id,/menuwith child routes,/payouts,/settings, a not-found route, with lazy loading per area. Show the route configuration. - Explain functional guards (
canActivate,canMatch,canDeactivate) and resolvers. Why is a guard not security (the API must check), and what iscanMatchgood for? - Component input binding (
withComponentInputBinding): route params, query params and resolved data asinput()s. What are the alternatives for loading data on navigation (resolvers vs loading in the component with a resource), and their UX trade-offs?
T5. Reactive forms and validators
- Explain
FormControl,FormGroup,FormArray, typed forms andnonNullable. P5's form had a disabled phone control:form.valueomitted it whilegetRawValue()included it. Why, and which do you send to the API? - Write synchronous validators (required, max length, Indian PIN code), a cross-field validator (pickup time must be after the kitchen opens), and an async validator (is this PIN deliverable?). P5: immediately after setting the PIN the control's status was
PENDING, thenINVALIDwithnotDeliverableafter 50 ms. How do you show pending and errors accessibly (chapter 20)? - When do you choose template-driven forms, reactive forms, or Angular's signal-based forms (introduced experimentally in v21)?
T6. RxJS
- Explain Observables (lazy, push-based streams of zero or more values), subscription and unsubscription, hot vs cold, and Subjects (
Subject,BehaviorSubject,ReplaySubject). - The lab compared
mergeMap,concatMap,switchMapandexhaustMapon a search box. Pick the operator for: search-as-you-type, "Place order" (pressed twice), saving each menu edit in order, loading details for several dishes in parallel, and polling order status every 10 s until delivered. - How do you avoid subscription leaks in Angular (
asyncpipe,takeUntilDestroyed,toSignal), and which RxJS operators do you need for error handling and retries (catchError,retrywith delay,timeout)?
T7. Signals and how they relate to RxJS
- The lab's signals experiment showed
cart().push(…)(mutation) did not update the total, whilecart.update(c => [...c, x])did. Explain signals' equality check,computed(lazy, memoised),effect(scheduled, for side effects), and why mutation breaks them. - P8 used
linkedSignal: the delivery slot defaulted to the kitchen's first slot (12:30), the user picked 13:00, and changing the kitchen reset it to 19:00. ExplainlinkedSignal, and compare withcomputed(read-only) and aneffectthat sets a signal (the anti-pattern). - "Signals for state, RxJS for events over time" (the lab). Classify: the cart, a search query's debounced results, the logged-in user, WebSocket messages, form values, route params, a countdown timer. How do
toSignal,toObservable,resource,rxResourceandhttpResourcebridge the two?
T8. Change detection
- How does Angular change detection work (walk the component tree, re-evaluate template bindings, update the DOM where values changed), and what triggers it with zone.js (any async event) versus zoneless (the default in new apps since v21: signals, template events,
asyncpipe,markForCheck)? - P3: an
OnPushchild bound to[dish]="line"showed "Idli 1" after the parent mutatedline.qty, and "Idli 3" after the parent replaced the object. Explain OnPush and why immutable inputs (or signals) matter. - Why did P2's template method run on every check, and what are the costs of expensive template expressions? What is
ExpressionChangedAfterItHasBeenCheckedErrortelling you?
T9. SSR, hydration and HttpClient
- Explain Angular SSR and hybrid rendering: per-route render modes (
RenderMode.Server,Prerender,Client) in server routes config, incremental hydration with@defer (hydrate on viewport), and event replay. Choose render modes for the partner portal and for a public kitchen profile page. - Why does SSR need
HttpClienttransfer cache (avoid fetching the same data twice: once on the server, once on hydration), and what must not be cached or transferred (personal data in shared caches, auth headers)? - P6's interceptors added
Authorization: Bearer demo-tokento every request and retried GETs on 503: the server saw two 503s and then a 200, all with the header. Write interceptors for auth, retries (idempotent methods only), timing/logging, and error mapping, and explain ordering.
T10. Testing and tooling
- Explain Angular testing: TestBed (configuring providers and components), component harnesses (CDK
HarnessLoaderfor Material and custom components),HttpTestingController, testing signals and zoneless change detection (await fixture.whenStable()), and the test runners (Vitest as the CLI default since v21, Karma deprecated; Jest; Web Test Runner). - What does the CLI build do (esbuild-based application builder, Vite dev server, budgets,
ng generate,ng update, environment configuration), and what are bundle budgets? - Angular's style guide naming (since v20:
order-list.tsforOrderListcomponent, no.componentsuffix) and why consistency matters in large teams.
Programming exercises
P1. The DI hierarchy, observed
Create a CartService with providedIn: 'root' and an instance id, a CartView and an Adder that inject it, and a ScopedCart component with providers: [CartService] containing its own Adder and CartView. Render one root-level pair and two ScopedCarts; add items in different places and record which views change. Then use the pattern for a real case: a "compare two kitchens" page where each panel has its own filter state.
P2. Pure pipes, impure pipes and template methods
Display a price three ways in one template: a pure rupees pipe, the same pipe with pure: false, and a method fmt(price). Count calls of each across five clicks on an unrelated button. Then build a 200-row orders table with three formatted columns and measure change-detection time with each approach.
P3. OnPush and mutable inputs
Make a parent pass an object to an OnPush child with a signal input. Mutate the object's property in the parent and observe the child; then replace the object. Fix the parent to use immutable updates with a signal, and write a test proving the child updates.
P4. A tooltip directive and a role directive
Write an attribute directive [appTooltip]="text" that shows an accessible tooltip on hover and focus, dismisses on Escape, and links with aria-describedby (chapter 20's T9), using host bindings. Then write a structural directive *appIfRole="'owner'" that renders its template only for owners, reading a session signal. Explain why the second is UX, not security.
P5. A typed reactive form with sync, cross-field and async validation
Build the "kitchen delivery settings" form: name (required, max 40), PIN code (Indian format, async "deliverable" check with debounce), opening and closing times (closing after opening), a disabled verified phone, and a FormArray of delivery slots. Record status transitions and compare value with getRawValue(). Display errors accessibly.
P6. HttpClient: interceptors, retries and resources
Add interceptors for auth and retry-on-503 (GET only), and load a dish with httpResource keyed by a dishId signal. With Playwright's page.route, make the first two requests return 503, then switch dishId twice within 30 ms with a slow response for the first. Record what the server saw, which requests were aborted, and what the template shows. Handle loading and error states correctly.
P7. Routes with guards, lazy loading and unsaved-changes protection
Implement T4's route table with an authGuard (redirect to login with a return URL), a roleGuard('owner') using canMatch, a canDeactivate guard for the menu editor ("You have unsaved changes"), and component input binding for :id. Verify in the build output that each area is a separate chunk, and that a non-owner never downloads the payouts chunk.
P8. Signals: computed, effect, linkedSignal
Model the checkout's delivery slot: kitchen (signal), slots (computed from kitchen), slot (linkedSignal defaulting to the first slot), total (computed from the cart and a delivery fee depending on the slot). Record the slot after the user picks the second slot and after the kitchen changes. Then implement "keep the user's slot if the new kitchen also offers it", and replace an existing effect-that-sets-a-signal with linkedSignal.
P9. Test a component with TestBed, harnesses and HttpTestingController
Test the orders page: it loads /api/orders?status=new, shows a list, and "Accept" sends POST /api/orders/{id}/accept and moves the order to "Preparing". Use provideHttpClientTesting, HttpTestingController, zoneless whenStable(), a component harness (CDK) or role-based queries, and verify no unexpected requests. Add a test for the 409 conflict path ("Order already accepted by another device").
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–23)
C1. The partner portal's orders area in Angular
Build the kitchen's orders area: lazy-loaded routes (list and detail), a root OrdersStore service with signals fed by SSE (chapter 19) and HTTP, exhaustMap for Accept (no double accepts), optimistic moves with rollback on 409 and ETags (chapter 19's T4), an accessible order board with keyboard alternatives (chapter 20, chapter 21's C3), OnPush everywhere, @defer for the analytics panel, interceptors (P6), and tests (P9) plus Playwright journeys with axe.
Combines: real-time and HTTP semantics (ch 19), accessibility (ch 20), UI architecture (ch 21), Volume 1's idempotency (ch 11) and this chapter.
C2. Compare the same feature in React and Angular
Implement the "menu editor" (list of dishes, edit form with validation, image upload, unsaved-changes guard, optimistic save with conflict handling) in both React (chapter 22) and Angular. Compare lines of code, bundle size (initial and lazy chunk), number of dependencies, time to implement, test effort, accessibility results, and how each framework's defaults helped or hurt. Write a one-page comparison for the architecture team.
Combines: React (ch 22), UI architecture (ch 21), forms and validation (ch 13, 16), HTTP conflicts (ch 19), accessibility (ch 20) and this chapter.
C3. Migrate an old Angular app to modern Angular
The payouts module is Angular 14-era code: NgModules, *ngIf/*ngFor without trackBy, constructor injection, BehaviorSubject stores with manual subscribe in components (leaks), zone.js with default change detection, Karma tests, and a SharedModule that imports everything. Plan and execute the migration to standalone, built-in control flow, inject(), signals (with toSignal where RxJS stays), OnPush, zoneless, Vitest and lazy routes, using ng update and Angular's migration schematics, and measure bundle size, change-detection cost and leaks before and after.
Combines: Volume 1's incremental refactoring and testing (ch 01, 10), UI architecture's dependency rules and barrels (ch 21's P7, P8), performance measurement (ch 18) and this chapter.
What the chapter leaves out
Angular Material, the CDK and accessibility utilities
Angular Material implements Material Design components (buttons, form fields, tables, dialogs, date pickers, autocomplete) with accessibility and theming (design tokens via Sass and CSS variables). The CDK (Component Dev Kit) provides unstyled building blocks: overlays and positioning, a11y (FocusTrap, LiveAnnouncer, FocusMonitor, ListKeyManager for roving focus), drag and drop with keyboard support, virtual scrolling, layout breakpoints, portals, and test harnesses. Angular Aria (headless accessible directives, introduced in v21) adds patterns like combobox, listbox, tabs and menus. A custom design system can be built on the CDK and Angular Aria, the Angular equivalent of chapter 21's headless libraries.
State management libraries: NgRx and friends
For large apps, NgRx offers the Redux-style Store (actions, reducers, effects, selectors) and the lighter SignalStore (@ngrx/signals: signalStore(withState(…), withComputed(…), withMethods(…)) with entity helpers), plus DevTools integration. Alternatives include NGXS, Elf, TanStack Query for Angular, and plain signal services (often enough). The choice depends on team size, the need for time-travel debugging and event logs, and how much server state there is (chapter 25 compares approaches across frameworks).
Internationalisation with $localize
Angular's built-in i18n marks text in templates (<h1 i18n="@@ordersTitle">Orders</h1>) and code ($localize), extracts messages to XLIFF/JSON with ng extract-i18n, and builds one bundle per locale at build time (no runtime translation cost), with ICU expressions for plurals and selects and locale data for pipes (currency, date with en-IN, hi, te). Runtime-switching libraries (Transloco, ngx-translate) trade build simplicity for switching languages without reload. For TiffinBox's Indian languages, combine with the chapter 21 gaps' i18n architecture.
Angular and Web Components, micro-frontends
Angular Elements (createCustomElement) packages Angular components as custom elements usable in any page (chapter 21's T9), e.g. embedding an Angular order widget in a React app or a CMS page; with zoneless and standalone, the runtime overhead is smaller than it used to be. Micro-frontend setups use Native Federation or Module Federation with Angular to compose separately deployed apps, with the trade-offs covered in chapter 21's gaps and chapter 30.
Security features built into Angular
Angular sanitises values bound to [innerHTML], [style], URLs and resource URLs by default (strip scripts, block javascript: URLs), and supports Trusted Types and strict CSP (with ngCspNonce/CSP_NONCE for inline styles). bypassSecurityTrustHtml and friends disable this and must be reviewed. HttpClient supports XSRF token cookies-to-header automatically (withXsrfConfiguration) for same-origin requests. Templates compiled AOT avoid runtime template compilation (and the eval-like risks of JIT). Chapter 28 covers frontend security in depth.
Senior exercises
S1. Choose Angular or React for a new product line
TiffinBox is starting a B2B product (corporate meal plans: admin dashboards, approval workflows, invoicing, many forms, 30+ screens), with two teams of six, one experienced in Angular, one in React. The existing customer app is React. Write the decision memo with criteria, options (Angular, React with a standard stack, both), risks and a recommendation.
S2. Review an Angular pull request
A PR adds a payouts table: a component with default change detection subscribing to this.http.get('/api/payouts') in ngOnInit and assigning to a field (no unsubscribe), *ngFor with no trackBy (old syntax), {{ formatAmount(p.amount) }} in each row, [innerHTML]="p.note", a BehaviorSubject store mutated with store.value.push(p), a canActivate guard as the only protection of payouts, and a setTimeout that sets this.loading = false (zoneless app). Write the review.
S3. Plan a zoneless migration for a large app
A 300-component Angular app with zone.js, default change detection, many third-party libraries (charts, maps, a date picker) and some setTimeout-based UI code needs to go zoneless. Plan: discovery (what relies on zones), the order of changes, tooling, testing, rollout, and how to measure benefits.
S4. Design the partner portal's state and data layer
Design how the partner portal handles data: server state (orders, menu, payouts) and client state (filters, drafts, UI), real-time updates, caching and invalidation, optimistic updates, error handling, offline tolerance for kitchen tablets with flaky Wi-Fi, and testing. Decide between plain signal services with resources, NgRx SignalStore, and TanStack Query for Angular.
S5. Teach Angular to React developers
Prepare a 30-minute session mapping React concepts to Angular for the React team joining the B2B product: components, props/inputs, state/signals, effects, context/DI, hooks/services, keys/track, memo/OnPush and computed, Suspense/@defer and resources, error boundaries/ErrorHandler, router, forms, testing. Include three gotchas from this chapter's outputs and end with five rules.