Angular Deep Dive — Internals for the 9-Year Engineer
"Every hard Angular question is one of three questions in disguise: when does it re-render, who owns this instance, and what is still subscribed. Answer those three and the rest is syntax."
01 · Why this chapter existsYou Have Shipped Angular For Years — Nobody Ever Showed You the Loop
This chapter teaches what Angular does between your code changing a value and the pixel changing on screen, and then drills two hundred senior questions on it. It assumes you can already build components; it does not assume you know why they re-render.
You have shipped Angular applications. You have written hundreds of components, argued about folder structure, migrated a codebase or two, and fixed production bugs at unreasonable hours.
And the senior interview keeps finding the same gap.
Why did that component not re-render when the array changed? Why does the same service behave like two different services on this screen? Why did the memory climb for six hours and then the tab died? Why is the bundle 1.8 MB when the app has eleven screens? What exactly does hydration do, and what breaks when it fails?
These are not trivia questions. They are the questions you answer every time you debug something hard, and answering them from memory rather than from experiment is what the senior title actually buys the employer.
The three questions everything reduces to
Angular is a large framework with a small number of mechanisms. Almost every difficult question is one of three, and it helps enormously to notice which one you are being asked.
| The question | The mechanism | Symptoms when you get it wrong | Section |
|---|---|---|---|
| When does it re-render? | Change detection: dirty marking, OnPush, the signal graph, the scheduler |
Stale screens, ExpressionChangedAfterItHasBeenChecked, a page that burns CPU while idle |
02, 03 |
| Who owns this instance? | The injector hierarchy: root, route, component, element | Two panels showing different data, state that will not reset, NG0201, memory that never frees | 04 |
| What is still subscribed? | RxJS subscriptions, effects, resources, DOM listeners, third-party widgets | Leaks, duplicate requests, handlers firing after navigation, a slow app that started fast | 05, 06 |
Sections 07 and 08 then cover the two things a senior is expected to own beyond correctness: what the user downloads, and what the server sends first.
What is in the box, and what has changed
Angular in September 2026 is not the framework most engineers learned. If your mental model was formed before 2024, three of its load-bearing assumptions are now false.
Zone.js is no longer how Angular knows things changed. Zoneless became stable in Angular 20.2 and is the default from Angular 21. New applications ship without it.
OnPush is no longer an optimisation you opt into. As of Angular 22 it is the default strategy, and the old always-check behaviour is what you opt into, under the name ChangeDetectionStrategy.Eager.
Reactive state is no longer RxJS by default. Signals cover component state, derived values and data fetching; RxJS keeps the problems it was always best at, which are streams, time and coordination.
None of that makes the old knowledge worthless. Every large codebase you will join is somewhere in the middle of this migration, so you need both models and you need to know which one a given file is written in.
How the page is organised
The primer — sections 02 to 08 — teaches the internals in plain words, with diagrams of the actual mechanisms rather than boxes with names in them.
The drill — sections 09 to 12 — is two hundred questions in four blocks: reactivity and rendering, dependency injection and asynchronous work, the application layer of forms and routing and state and tests, and finally performance and design.
Every answer is collapsed behind a Reveal answer control, and every answer carries the follow-ups an interviewer reaches for next. Say your answer out loud in full sentences before you open the panel. The gap between what you said and what you read is the part your memory keeps.
Where a topic belongs to a neighbouring chapter, this page links rather than repeats. The language and the from-zero material live in E14 · Angular Primer; the framework-agnostic architecture and the React comparison live in E16 · Frontend Design; JavaScript's own semantics live in E11.
Version facts are stated as of September 2026: Angular 22 is current, released June 2026. Signals became stable in v20, zoneless in v20.2 and default in v21, Vitest replaced Karma as the default runner in v21, and Signal Forms plus resource, rxResource and httpResource became stable in v22.
Quick reference — Orientation
- The three questions
- When does it re-render, who owns this instance, what is still subscribed. Nearly every hard Angular problem is one of these.
- Zoneless
- Stable in v20.2, default in v21. Angular no longer patches browser APIs to guess that something changed.
OnPushby default- Since v22. The always-check strategy is now the opt-in, named
Eager. - Signals vs RxJS
- Signals own state and derivation. RxJS owns streams, time, cancellation and coordination. They interoperate through
toSignal,toObservableandrxResource.
02 · The primerChange Detection, Honestly — From Monkey-Patching to a Dirty Flag
Change detection is the pass where Angular walks the component tree, re-evaluates every binding it did not skip, and writes the differences to the DOM. Everything that has changed in the last three years is about which components it skips.
Start with the thing that is easy to get wrong in an interview: change detection does not detect changes.
It re-evaluates bindings and compares each result with what it stored last time. If they differ, it updates the DOM. There is no observation of your fields, no proxy, no diffing of a virtual tree.
So the entire performance story is about how many bindings get re-evaluated and how often — and that is decided by two things: what triggers a pass, and which components a pass is allowed to skip.
What a single pass actually does
When Angular checks one component, it runs a function the compiler generated for that component's template. That function is ordinary JavaScript, and it is worth knowing roughly what it contains.
// Your template: <h3>{{ title() }}</h3> <button [disabled]="busy()">Save</button>
// Roughly what Angular runs on each check of this component:
function TaskCard_Template(renderFlags, ctx) {
if (renderFlags & RenderFlags.Create) {
// Runs ONCE: create the elements and attach listeners.
elementStart(0, 'h3'); text(1); elementEnd();
elementStart(2, 'button'); text(3, 'Save'); elementEnd();
}
if (renderFlags & RenderFlags.Update) {
// Runs on EVERY check: evaluate, compare, write only if different.
advance(1); textInterpolate(ctx.title());
advance(1); property('disabled', ctx.busy());
}
}
Read the update branch. textInterpolate and property each keep the previous value in a slot on the component's internal view array. They compare, and they touch the DOM only when the comparison fails.
That is why a check of an unchanged component is cheap but not free: the expressions still run, the comparisons still happen, and only the DOM write is skipped.
It is also why calling a method from a template is expensive. ctx.filteredTasks() as a method runs the whole filter every time this update branch runs, and the comparison then fails anyway because a fresh array has a fresh identity.
What triggers a pass — the old answer
Zone.js was a library that replaced the browser's asynchronous APIs with wrapped versions. Every setTimeout, every addEventListener, every promise, every XMLHttpRequest. It patched them at startup, before your code ran.
The wrapper's job was to notice when the last asynchronous task in a batch finished, and then tell Angular: something completed, so something may have changed.
Angular's response was the only one available to it. It ran change detection from the root of the tree, checking every component on the way down.
Two costs came out of that design. The obvious one is work: a screen with two thousand bindings does two thousand comparisons because a tooltip's timer fired. The subtle one is that the patching was invasive — stack traces went through zone frames, some third-party libraries misbehaved, and about 15 KB of JavaScript shipped to every user to make it work.
What triggers a pass — the current answer
A zoneless application schedules a change detection pass when one of a short, knowable list of things happens.
- A signal read by a template changes value. The signal notifies its consumers, and a template consumer marks its component dirty.
- A template event handler runs — a
(click), a(input). Angular marks that component dirty after the handler returns. - Something calls
markForCheck()orApplicationRef.tick()explicitly. - An async pipe emits, a resource settles, or a route activates — each of which internally does one of the above.
The pass itself is then scheduled rather than immediate. Angular coalesces several triggers in the same task into one pass, which is why setting five signals in one function produces one render, not five.
That list is short enough to memorise, and memorising it is what lets you answer "why did this not update" without a debugger. If the change is not on that list, Angular does not know about it.
Which components a pass may skip
Once a pass starts at the root, Angular walks down. At each component it asks whether it may skip this subtree.
The rule is the same whether you arrived here from Zone.js or from a signal, and it is worth being exact about it.
| Trigger | What actually happens |
|---|---|
| An input changed by reference | The parent's update pass compares the bound expression with its stored value using Object.is. A different reference marks the child dirty. |
| An event fired inside the component | Angular marks the component dirty and every ancestor up to the root, so the pass can reach it. |
| A signal read by its template changed | The signal's consumer list includes this component's view; it is marked dirty and its ancestors marked to be traversed. |
markForCheck() was called |
Identical to the event case: mark this view dirty, mark the path to the root as needing traversal. |
An async pipe in its template emitted |
The pipe calls markForCheck() for you. This is the entire reason the async pipe works with OnPush and a manual subscribe does not. |
Notice the phrase "marks the path to the root". A dirty flag on a leaf would be useless on its own, because the pass would never walk down to find it. So marking is two operations: dirty on this view, and has a dirty descendant on each ancestor.
The two-pass verification that produces the famous error
In development mode Angular runs each change detection pass twice and compares the results. If a binding produced a different value the second time, it throws ExpressionChangedAfterItHasBeenCheckedError.
This is not Angular being fussy. It is catching a real bug class: a value that is still settling when it is rendered means the DOM you shipped does not match the state you have, and which one wins becomes timing-dependent.
There are exactly three common causes, and each has a different fix.
| Cause | Example | Fix |
|---|---|---|
| A child writes to a parent's state after the parent rendered | A child emits in ngAfterViewInit, the parent sets a field the template already showed |
Move the write to an event, or derive it with computed so there is nothing to write |
| A template expression returns a new object each call | [style]="{ width: w + 'px' }" or a getter that builds an array |
Hoist it into a computed so the identity is stable between the two passes |
| Something is set inside a lifecycle hook that runs mid-pass | ngAfterViewInit measuring an element and setting a signal that the template reads |
afterNextRender, which runs after the pass completes rather than inside it |
What not to do is wrap the write in setTimeout. It silences the error by moving the write into the next task, which means the user sees one frame of the wrong value and you have converted a loud bug into a quiet one.
A classic Zone.js incident. A third-party library polls with setInterval every 100 milliseconds. Zone.js patched setInterval, so every tick tells Angular that something may have changed, and Angular checks the whole tree — ten times a second, forever, on a page the user is only reading.
Under Zone.js the fix was ngZone.runOutsideAngular(() => { ... }), which runs the callback in a zone Angular does not watch, and then ngZone.run(...) around only the part that genuinely changes state.
Zoneless removes the problem at the root: an unpatched setInterval triggers nothing at all. The interval can only cause a render by setting a signal, which is exactly the behaviour you wanted.
This is the strongest single argument for zoneless, and it is worth having a story like it ready — interviewers respond much better to "we had a page at 30% idle CPU and here is what it was" than to a recital of the benefits.
What you actually do about OnPush now
Since Angular 22 the answer is mostly "nothing", because it is the default. But you still need to know the contract, because breaking it is how stale screens happen.
The contract is: this component's rendered output depends only on its inputs, its own signals, and events inside it.
You break it by mutating an object that was passed in as an input. The reference does not change, so the parent's comparison passes, so the child is never marked dirty, so the screen keeps the old value while the data is new.
You also break it by holding state in a plain field that something outside Angular writes — a WebSocket handler, a third-party callback, a promise from a library. Nothing marks the component, so nothing re-renders.
Both fixes are the same one: put the state in a signal, and replace rather than mutate.
Quick reference — Change detection
- What a pass does
- Runs each checked component's generated update function: evaluate every binding, compare with the stored previous value, write the DOM only on a difference.
- Zone.js
- Patched every async browser API to report "something finished", forcing a whole-tree check. About 15 KB, invasive, and the cause of idle-CPU bugs. Optional since v20.2, gone by default from v21.
- Zoneless triggers
- A signal read by a template changes; a template event handler runs;
markForCheck()ortick()is called; an async pipe emits or a resource settles. Nothing else causes a render. - Marking is two operations
- Dirty on the view itself, plus has a dirty descendant on every ancestor — otherwise the pass would never walk down to it.
OnPushcontract- Output depends only on inputs, own signals and internal events. Mutating an input object breaks it silently. Default since v22; the old behaviour is now
Eager. - ExpressionChangedAfterItHasBeenChecked
- The development-mode second pass produced a different value. Causes: a late write to already-rendered state, an expression returning a new object each call, or a lifecycle hook setting state mid-pass. Never fix it with
setTimeout. markForCheckvsdetectChangesmarkForCheckflags the view and its ancestors for the next scheduled pass.detectChangesruns a check on this view now, synchronously, bypassing the scheduler.
03 · The primerThe Signal Graph — Push the Rumour, Pull the Value
Signals form a graph of producers and consumers. A change pushes a "you may be stale" notification down the graph, and the actual value is only recomputed when somebody reads it. That split is what makes the system both correct and cheap.
Most people can use signals after ten minutes. The interview questions are about what happens between the set and the render, and there are four behaviours that only make sense once you have seen the graph.
The graph, and what each node stores
Every signal, computed and effect is a node. A producer is anything that can be read; a consumer is anything that reads. A computed is both.
Each node stores a small amount of bookkeeping, and knowing the four pieces explains almost every behaviour.
- A version number, incremented whenever the producer's value actually changes.
- A list of its consumers, so a change can be announced downward.
- For a consumer, a list of its producers with the version it last saw from each.
- A state: clean, "maybe dirty", or dirty.
The version numbers are the part people miss, and they are what make the system avoid unnecessary work — a consumer that finds every producer at the same version it last saw can skip recomputing entirely, even after being told it might be stale.
Push, then pull
When you call set on a signal, Angular does not recompute anything that depends on it. It walks the consumer list and marks each one "maybe dirty", then walks their consumers and marks those too. That is the push.
Nothing is evaluated. The whole operation is flag-setting, so setting a signal that feeds a hundred computeds costs a hundred flag writes and zero calculations.
Later, when something reads a computed, the pull happens. The computed sees it is "maybe dirty", so it asks each of its producers for their current version. If every version matches what it recorded, it is genuinely clean and returns its cached value. If any differs, it re-runs its function.
import { signal, computed } from '@angular/core';
let expensiveRuns = 0;
const items = signal([1, 2, 3]);
const total = computed(() => { expensiveRuns++; return items().reduce((a, b) => a + b, 0); });
console.log(expensiveRuns); // 0 -- creating a computed runs nothing
items.set([1, 2, 3, 4]);
console.log(expensiveRuns); // 0 -- setting only pushed a flag
console.log(total()); // 10 -- the read pulled, so it ran
console.log(expensiveRuns); // 1
console.log(total(), total()); // 10 10 -- cached, no re-runs
console.log(expensiveRuns); // 1
items.set([1, 2, 3, 4]); // a NEW array with the same contents
console.log(total()); // 10
console.log(expensiveRuns); // 2 -- ran again: the array identity changed
Read the last block. The final set passed an array with identical contents but a different identity. Object.is says they differ, so the version bumped and the computed re-ran.
That is the cost of reference equality and it is usually the right trade. When it is not — a computed that rebuilds an equivalent object every time and causes real downstream work — you can pass a custom equal function to stop the propagation there.
Why the graph is glitch-free
Here is the behaviour that separates a proper reactive system from a naive one, and it is a favourite interview question.
const width = signal(10);
const height = computed(() => width() * 2); // depends on width
const area = computed(() => width() * height()); // depends on BOTH
// area is 10 * 20 = 200. Now:
width.set(20);
// A naive system might recompute area as soon as width changes,
// while height still holds its old value: 20 * 20 = 400. That is a GLITCH --
// a value that never corresponds to any consistent state of the inputs.
console.log(area()); // 800 -- always 20 * 40. The intermediate is never observable.
Angular's graph cannot produce that intermediate value, because nothing is computed during the push. By the time area is pulled, it asks height for its value, and height notices it is stale and recomputes first.
The dependencies are resolved depth-first at read time, so every consumer always sees a fully settled set of producers.
A computed can never observe a partially updated world. That guarantee is why deriving state is safe in a way that a chain of manual update callbacks never is.
area is never computed against a stale height. The glitch value 400 does not exist at any point in time.Dependencies are dynamic, not declared
A computed's dependency list is rebuilt on every execution, from the reads that actually happened. It is not a static list, and that has a consequence people find surprising.
const useMetric = signal(true);
const celsius = signal(20);
const fahrenheit = signal(68);
const shown = computed(() => useMetric() ? celsius() : fahrenheit());
shown(); // 20. Dependencies recorded THIS run: useMetric, celsius.
fahrenheit.set(100); // Nothing happens. fahrenheit is not currently a dependency.
shown(); // 20, cached, no recompute.
useMetric.set(false); // useMetric IS a dependency, so shown is invalidated.
shown(); // 100. Dependencies re-recorded: useMetric, fahrenheit.
// celsius is now NOT a dependency and cannot invalidate it.
Read the middle step. Setting fahrenheit while the metric branch is active does nothing at all — not a wasted recompute, not a marked flag. The dependency genuinely does not exist while that branch is not taken.
This is efficient and it is also a trap: a computed with an early return can silently stop tracking something, and the bug looks like "this value updates sometimes".
untracked — reading without subscribing
Sometimes you need a signal's current value inside a reactive context without that read creating a dependency.
import { effect, untracked } from '@angular/core';
effect(() => {
const id = this.selectedId(); // tracked: re-run when the selection changes
// We want the current user for the log line, but we do NOT want a user change
// to re-fire this effect.
const user = untracked(() => this.currentUser());
this.analytics.track('selection', { id, user: user.id });
});
Without untracked, that effect would re-run on every change to currentUser and send a duplicate analytics event that no user action caused.
The rule: track the things that should cause the work; untrack the things you merely need the value of.
Effects: when they run, and why that matters
An effect does not run synchronously when its dependency changes. It is queued and run as part of the change detection cycle, after the render.
Three consequences follow, and each has produced a real bug.
Several changes in one task produce one run. Setting four signals an effect reads inside one function queues the effect once, not four times. That coalescing is usually what you want and occasionally what confuses you when counting log lines.
The DOM is already updated when it runs. That makes effects a reasonable place to measure or scroll, although afterNextRender is the more precise tool.
Cleanup runs before the next execution. An effect's function receives an onCleanup callback, which is how you cancel the previous piece of work before starting a new one.
effect((onCleanup) => {
const id = this.roomId();
const socket = new WebSocket(`wss://chat.example.com/rooms/${id}`);
socket.onmessage = (e) => this.messages.update(m => [...m, JSON.parse(e.data)]);
// Runs before the next execution, and once more when the effect is destroyed.
onCleanup(() => socket.close());
});
Without that cleanup, changing rooms five times leaves five open sockets all writing into the same message list. It is the signal-era version of the subscription leak.
Where signals are the wrong tool
A senior answer includes the limits, and there are three worth naming.
Signals have no notion of time. There is no debounce, no throttle, no "wait for both of these", no retry with backoff. Angular 22 added a debounced() helper for the commonest case, but anything more coordinated is an RxJS problem.
Signals have no notion of events. A signal holds a current value. "The user clicked save, three times" is not a value, it is a sequence, and forcing it into a signal loses the repeats.
Signals are synchronous. Asynchronous work needs the resource APIs on top, which is exactly what resource, rxResource and httpResource are.
Quick reference — The signal graph
- Producers and consumers
- Every node stores a version number, its consumers, its producers with last-seen versions, and a clean / maybe-dirty / dirty state.
- Push then pull
setonly marks consumers "maybe dirty" — no computation. A read resolves depth-first, comparing versions, and recomputes only what genuinely changed.- Glitch-free
- Because nothing computes during the push, a computed can never observe a half-updated world. The diamond's intermediate value does not exist.
- Dynamic dependencies
- The dependency list is rebuilt from the reads that actually happened. A branch not taken is not a dependency, so changing it does nothing.
untracked- Read a value without creating a dependency. Track what should cause the work; untrack what you merely need the value of.
- Effect timing
- Queued, not synchronous; coalesced within a task; runs after the DOM is updated; its
onCleanupcallback runs before the next execution and on destroy. - What signals cannot do
- Time, sequences of events, and asynchrony. Those remain RxJS territory, bridged by
toSignal,toObservableand the resource APIs.
04 · The primerDependency Injection, Deeply — Two Trees, One Search Order
Angular has two parallel injector hierarchies, not one. Knowing which tree a provider lives in, and the order the search visits them, explains every "no provider" error and every "why are there two instances" bug you will ever file.
Most developers hold a simplified model: there is a chain of injectors, the search goes up, root is at the top. That model is right about ninety percent of the time, and the other ten percent is where the hard bugs live.
The two trees
Angular maintains two separate hierarchies, and they are searched one after the other.
The ElementInjector tree follows your component structure. Every component and directive gets a node, and its parent is the component that rendered it. Providers you list in a @Component({ providers: [...] }) array live here.
The EnvironmentInjector tree follows your application's configuration structure. The root environment injector holds everything from app.config.ts and every providedIn: 'root' service. Lazy-loaded routes with their own providers create child environment injectors.
The search order is precise, and it is worth memorising because it is the answer to a whole family of questions.
- Walk up the ElementInjector chain, from the requesting component to the root component.
- If nothing was found, jump to the EnvironmentInjector associated with that part of the tree, and walk up that chain to the root environment injector.
- If still nothing, reach the NullInjector, which exists only to throw
NG0201: No provider for X.
The four resolution modifiers
You can change that search. inject() takes options, and the old decorators do the same thing.
| Option | What it does | Real use |
|---|---|---|
{ self: true } |
Look only in this component's own injector; do not walk up | A directive that must be on the same element as a provider, and should fail loudly otherwise |
{ skipSelf: true } |
Start the search at the parent, ignoring this injector | A service that wants the parent instance of itself — recursive tree components, nested form groups |
{ optional: true } |
Return null instead of throwing when nothing is found |
Optional collaborators: a logger, an analytics sink, a parent that may not exist |
{ host: true } |
Stop the element search at the host component boundary | A directive that may use a provider from its host component but must not reach into the wider app |
The one worth a worked example is skipSelf, because it enables a pattern you cannot build any other way.
import { Component, inject, computed } from '@angular/core';
@Component({
selector: 'app-panel',
providers: [Panel], // each panel provides ITSELF to its children
template: `<div [style.paddingLeft.px]="depth() * 12"><ng-content /></div>`,
})
export class Panel {
// Ask for a Panel, but start the search at my PARENT, and tolerate not finding one.
private readonly parent = inject(Panel, { skipSelf: true, optional: true });
readonly depth = computed(() => (this.parent?.depth() ?? -1) + 1);
}
Read why both options are needed. Without skipSelf, the panel would find itself — it is in its own providers array — and construct infinitely. Without optional, the outermost panel would throw, because it genuinely has no parent.
This is exactly how Angular's own nested form directives and the CDK's tree components work.
The injection context, and the rule everyone breaks
inject() works by reading a module-level variable that Angular sets while it is constructing something. That variable says "the thing currently being built is X, so resolve against X's injector".
Outside those windows the variable is unset, and inject() throws NG0203.
The windows where you are in an injection context are worth listing exactly, because the list is shorter than people assume.
- Field initialisers and the constructor body of a component, directive, pipe or service.
- Inside a
factoryfunction of a provider. - Inside route guards, resolvers and functional interceptors — the router and HTTP client establish a context before calling them.
- Inside the callback passed to
runInInjectionContext(injector, fn).
Notably absent: click handlers, setTimeout callbacks, promise continuations, and the body of an effect created outside a context.
export class ReportPage {
// OK -- field initialiser, we are in the injection context.
private readonly http = inject(HttpClient);
private readonly injector = inject(Injector); // capture it for later
export(): void {
// WRONG -- NG0203. This runs on a click, long after construction.
// const pdf = inject(PdfService);
// Right, when a lazy dependency really must be resolved later:
runInInjectionContext(this.injector, () => {
const pdf = inject(PdfService);
pdf.render();
});
}
}
In practice, needing runInInjectionContext in application code is a smell — inject the service as a field like everything else. It earns its keep in libraries, and when creating an effect or a resource outside a constructor.
Lifetime, and the leak nobody sees coming
Where a service is provided decides not just how many instances exist, but when they are destroyed — and a service that is never destroyed while holding a growing structure is a leak with no stack trace.
| Provided at | Instances | Destroyed when | Watch out for |
|---|---|---|---|
providedIn: 'root' |
One per application | Never, until the tab closes | Caches and log arrays that only grow; subscriptions started in the constructor |
Route providers |
One per activation of the route subtree | On navigating out of the subtree | Re-entering the route gives a fresh instance — deliberate, but surprising if you cached in it |
Component providers |
One per component instance | With that component | A component inside @for gets one instance per row |
providedIn: 'platform' |
One per page, shared across multiple bootstrapped apps | Page unload | Rarely correct outside micro-frontend hosts |
A root service can clean up: implement ngOnDestroy, or use inject(DestroyRef).onDestroy(...). It just very rarely runs, so the discipline has to be to not accumulate in the first place.
Two mechanisms worth knowing by name
Multi-providers. A provider with multi: true contributes to an array rather than replacing the previous registration. Every registration for that token lands in one array, and injecting it returns all of them.
This is the extension-point mechanism: HTTP interceptors, application initialisers and error handlers are all built on it. It is what you reach for when the answer to "who can register one of these" is "anyone".
Circular dependencies and forwardRef. If A injects B and B injects A, construction cannot complete and Angular throws a cyclic dependency error.
forwardRef(() => B) only solves the narrower problem of a class being referenced before its declaration is evaluated — the parent-panel pattern above needs it in some file layouts. It does not solve a genuine cycle.
A genuine cycle is a design signal: the two services share a responsibility that belongs in a third, or one of them should receive what it needs as a method argument instead of injecting the other.
A team adds providers: [CartService] to a component while debugging, to get a clean cart in one test. The line survives review because it looks like configuration.
Six months later that component renders inside a product grid. Every card now has its own cart, the header's total never moves, and the bug report says "the cart badge is broken" — which sends three engineers to look at the badge.
The diagnostic is one line: inject the service in two places and log a === b. If it is false, stop reading the badge's code and go and find the second provider.
The general rule: a providers array on a component is a declaration that this state is per instance. If that is not what you mean, it does not belong there.
Quick reference — Dependency injection
- Two trees
- ElementInjector follows components; EnvironmentInjector follows configuration. The element chain is searched first and completely, then the environment chain, then NullInjector throws NG0201.
- Modifiers
selfhere only,skipSelfstart at the parent,optionalreturn null instead of throwing,hoststop at the host component.- Injection context
- Field initialisers, constructors, provider factories, guards, resolvers, functional interceptors, and
runInInjectionContext. Nowhere else — a click handler callinginject()is NG0203. - Lifetime
- Root lives forever; route providers die on leaving the subtree; component providers die with the component — one per instance, including one per row inside
@for. multi: true- Contributes to an array instead of replacing. The mechanism behind interceptors, initialisers and any "anyone can register one" extension point.
- Cyclic dependencies
forwardReffixes a declaration-order problem, not a real cycle. A real cycle means a shared responsibility belongs in a third service.- Two instances where you expected one
- Log
a === bfrom two injection sites. False means find the strayprovidersarray; do not debug the symptom.
05 · The primerRxJS for the Senior Engineer — Four Operators and Two Traps
Signals took over state, but RxJS still owns everything involving time, sequences and cancellation. The senior round reduces to two areas: choosing correctly among the four flattening operators, and knowing what is still subscribed.
RxJS has over a hundred operators and you need about fifteen. What separates a senior answer is not breadth — it is being exact about the four that choose a concurrency strategy, and honest about the two that leak.
The contract, restated precisely
An observable is a function that, when subscribed, starts producing notifications. There are exactly three kinds, and the sequence rule is strict.
Zero or more next notifications, then at most one of complete or error. After either terminal notification nothing more is ever delivered, and the subscription is torn down automatically.
That last clause is the source of the most-encountered RxJS surprise: an error terminates the stream permanently. A valueChanges pipeline that lets an HTTP error escape stops responding to the form forever, and the user sees a field that has simply stopped working.
// BROKEN: one failed request and this search box is dead until the page reloads.
this.form.controls.q.valueChanges.pipe(
debounceTime(250),
switchMap(q => this.api.search(q)), // if this errors, the outer stream errors
takeUntilDestroyed(),
).subscribe(results => this.results.set(results));
// CORRECT: catch INSIDE the inner observable, so the outer stream never sees an error.
this.form.controls.q.valueChanges.pipe(
debounceTime(250),
switchMap(q => this.api.search(q).pipe(
catchError(() => { this.error.set('Search failed'); return of([]); })
)),
takeUntilDestroyed(),
).subscribe(results => this.results.set(results));
Read where catchError sits. Inside the switchMap, wrapped around the inner request, it replaces that one failed request with an empty result and the outer stream continues.
Placed outside the switchMap instead, it would catch the error — and then the outer stream would still be terminated, because catchError returns a replacement observable for the whole thing. This placement question is one of the most reliable senior filters in an RxJS interview.
The four flattening operators
Every one of these takes a stream of values, maps each to an inner observable, and flattens the results into one output stream. They differ only in what they do when a new value arrives while a previous inner observable is still running.
That single difference is the whole decision, and getting it wrong produces bugs that look like race conditions.
| Operator | On a new value while one is in flight | Reach for it when | Canonical use |
|---|---|---|---|
switchMap |
Cancels the previous inner observable and switches to the new one | Only the latest result matters | Type-ahead search, loading a detail view from a route parameter |
mergeMap |
Runs both concurrently; results arrive in whatever order they finish | Every request must happen and order does not matter | Firing independent analytics events, parallel uploads |
concatMap |
Queues the new one until the previous completes | Every request must happen, in order | Sequential writes to the same record, an ordered command queue |
exhaustMap |
Ignores the new value entirely until the current one completes | Extra triggers are accidents you want dropped | A submit button being double-clicked, a login form |
The default should be switchMap for reads and exhaustMap for writes triggered by a button.
Using mergeMap for a type-ahead is the classic race-condition bug: two requests are in flight, the slower one was typed earlier, it lands last, and the user's search box shows results for a prefix they already deleted.
Using switchMap for a save is the classic data-loss bug: the second click cancels the first save, and depending on your backend, the first write may have already partly happened.
Cold, hot, and the duplicate-request trap
A cold observable creates its work per subscriber. http.get('/api/tasks') is cold: subscribe twice and two requests go out, because the recipe runs again from the top.
A hot observable shares one execution among all subscribers. A Subject is hot by nature; a cold observable becomes hot when you put a multicasting operator on it.
// The template uses the async pipe twice on the same observable:
// @if (user$ | async; as u) { {{ u.name }} }
// <app-avatar [user]="(user$ | async)!" />
// -> TWO HTTP requests, because each async pipe subscribes separately.
readonly user$ = this.http.get<User>('/api/me'); // cold
readonly user$ = this.http.get<User>('/api/me').pipe(shareReplay(1)); // shared
shareReplay(1) makes one subscription serve everyone and replays the last value to late subscribers. It is the right answer here, and it carries a trap worth stating exactly.
By default shareReplay never unsubscribes from its source. Even when every downstream subscriber has gone, it holds the source subscription and the replayed value forever. For an HTTP call that completes, this is harmless. For an interval or a WebSocket, it is a permanent leak.
The fix is shareReplay({ bufferSize: 1, refCount: true }), which drops the source subscription when the last subscriber leaves.
In modern Angular, the better answer to this whole family of problems is usually toSignal, which subscribes once, shares by construction, and unsubscribes on destroy.
The subjects, and which one you actually want
| Type | What a new subscriber gets | Use |
|---|---|---|
Subject | Only values emitted after it subscribed | Events: "the user saved", "a toast should appear" |
BehaviorSubject | The current value immediately, then subsequent ones | State — which is now nearly always a signal instead |
ReplaySubject(n) | The last n values, then subsequent ones | A short history: recent notifications, the last few log lines |
AsyncSubject | Only the final value, and only once the subject completes | Rare. A one-shot result several parties await |
The practical guidance for 2026: if you were about to reach for a BehaviorSubject, you want a signal. A signal is a current value with change notification, which is exactly what a BehaviorSubject was being used to fake, and it has no subscription to manage.
Keep Subject for genuine events, because an event that happens twice with the same payload is two events, and a signal would collapse them into one unchanged value.
What is still subscribed
Every observable that does not complete on its own keeps its subscriber alive, and in a component that means keeping the component alive.
The list of streams that never complete is short and worth memorising: router events, fromEvent listeners, interval and timer with a period, form valueChanges and statusChanges, WebSocket streams, and any Subject you own.
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
export class SearchBox {
private readonly form = inject(FormBuilder).group({ q: [''] });
constructor() {
// takeUntilDestroyed() with no argument requires an injection context,
// which the constructor provides. It ends the stream on destroy.
this.form.controls.q.valueChanges.pipe(
debounceTime(250),
distinctUntilChanged(),
takeUntilDestroyed(),
).subscribe(q => this.query.set(q ?? ''));
}
}
Its advantage over the old destroy$ subject plus ngOnDestroy pattern is that the cleanup is written at the point of subscription. Nobody has to remember to add a line in a distant method when they add a fourth subscription.
Outside a constructor, pass one in: takeUntilDestroyed(this.destroyRef), with destroyRef = inject(DestroyRef) as a field.
Crossing between signals and observables
| Function | Direction | Notes |
|---|---|---|
toSignal(obs$, { initialValue }) |
Observable → signal | Subscribes immediately, unsubscribes on destroy. Without initialValue the type includes undefined; requireSync: true asserts the source emits synchronously. |
toObservable(sig) |
Signal → observable | Emits on change. Values are delivered on the effect timing, so rapid changes within one task are coalesced — it is not a lossless event log. |
rxResource({ params, stream }) |
Both | Signal inputs drive an observable-producing function, and the result comes back as resource signals with loading and error. |
The coalescing note on toObservable matters. If you set a signal three times in one function and expect three emissions, you get one. Signals model state, and state has no notion of "it was briefly 2".
The most common RxJS anti-pattern in real Angular codebases is a subscribe inside a subscribe: fetch a user, then inside that callback fetch their orders.
It works, and it breaks three things. The inner subscription is never cleaned up by the outer one, so it leaks. Errors from the inner stream are invisible to the outer error handler. And there is no cancellation: if the user id changes, the previous inner request keeps running and can land after the newer one.
The fix is always a flattening operator — switchMap here, since only the latest user's orders matter. One subscription, one cleanup, one error path, and cancellation for free.
Quick reference — RxJS
- The contract
- Zero or more
next, then at most onecompleteorerror. An error terminates the stream permanently — a form pipeline that lets one escape stops working forever. catchErrorplacement- Inside the inner observable of a
switchMapto survive; outside it, the outer stream still dies. - The four flatteners
switchMapcancels the previous,mergeMapruns both,concatMapqueues,exhaustMapignores the new one. Reads want switch; button-triggered writes want exhaust.- Cold vs hot
- Cold re-runs per subscriber, so two
asyncpipes on one HTTP observable send two requests.shareReplay(1)shares — but addrefCount: truefor anything that does not complete, or it leaks. - Subjects
Subjectfor events,ReplaySubject(n)for a short history,AsyncSubjectrarely.BehaviorSubjectfor state is now a signal.- Streams that never complete
- Router events,
fromEvent,interval,valueChanges, WebSockets, your own subjects. All needtakeUntilDestroyed(). - Nested subscribe
- Leaks, hides errors and cannot cancel. Always a flattening operator instead.
- Interop
toSignalin,toObservableout,rxResourcefor signal-driven fetching.toObservablecoalesces rapid changes — it is state, not an event log.
06 · The primerState Management Architecture — Four Kinds of State, One Ladder
Most state-management arguments are really a failure to notice that "state" means four different things with four different owners. Sort them first, and the question of which library to use mostly answers itself.
The question "should we use NgRx?" is asked in every Angular architecture interview, and the weak answer is a preference. The strong answer starts by refusing the premise: it depends what state you mean.
The four kinds of state
| Kind | Examples | Who owns the truth | Where it lives |
|---|---|---|---|
| Server cache | The task list, the user profile, search results | The server. Your copy is always a stale snapshot | A resource, or a caching layer — not a global store you hand-maintain |
| URL state | Current page, sort column, filter text, selected tab | The address bar | Route and query parameters, read as component inputs |
| Local UI state | Is this accordion open, which row is hovered, an unsent draft | One component | A signal in that component. It should die with it |
| Shared client state | Signed-in user, feature flags, shopping cart, unsaved wizard progress | Your application | A service with signals, or a store library once it gets large |
The single most expensive architectural mistake in frontend work is treating server cache as shared client state. It looks reasonable: fetch the tasks once, put them in a global store, everything reads from there.
Then you own cache invalidation. Somebody edits a task in another tab. A background job changes a status. Two screens disagree. You start writing code to refetch on navigation, on focus, on a timer — and you have hand-rolled a caching library, badly, inside your state management library.
The correct frame is that server data is a cache with a freshness policy, and Angular's resource APIs are the built-in expression of that.
The ladder
Escalate only when the current rung actually hurts. Each step up buys something specific and costs boilerplate and onboarding time.
| Rung | What it is | Move up when |
|---|---|---|
| 1 · Component signals | signal and computed inside one component |
A sibling needs the same value, and lifting it to a shared parent would mean threading it through three layers |
| 2 · A service with signals | Private writable signal, asReadonly() view, methods as the only writers |
The service has grown past roughly ten methods, or several features need coordinated updates, or you cannot answer "who changed this" quickly |
| 3 · NgRx SignalStore | A structured signal store: state, computed, methods, and hooks, with entity helpers | You need time-travel debugging, strict action logging for audit, or a genuinely large shared state graph across many teams |
| 4 · NgRx global Store | The full Redux pattern: actions, reducers, selectors, effects | Rarely. Large multi-team applications where the action log itself is the debugging tool |
Most applications should live on rung two forever, and that is a defensible senior position rather than a lack of ambition.
Rung two, done properly
@Injectable({ providedIn: 'root' })
export class CartService {
// 1. One private source of truth.
private readonly _lines = signal<CartLine[]>([]);
// 2. A read-only public view -- consumers physically cannot call set().
readonly lines = this._lines.asReadonly();
// 3. Everything else is derived, so it cannot fall out of step.
readonly count = computed(() => this._lines().reduce((n, l) => n + l.qty, 0));
readonly subtotal = computed(() => this._lines().reduce((s, l) => s + l.qty * l.price, 0));
readonly isEmpty = computed(() => this._lines().length === 0);
// 4. A small, named write surface. These are the only mutations in the app.
add(product: Product, qty = 1): void {
this._lines.update(lines => {
const existing = lines.find(l => l.productId === product.id);
return existing
? lines.map(l => l === existing ? { ...l, qty: l.qty + qty } : l)
: [...lines, { productId: product.id, price: product.price, qty }];
});
}
setQty(productId: string, qty: number): void {
if (qty <= 0) { return this.remove(productId); }
this._lines.update(lines => lines.map(l => l.productId === productId ? { ...l, qty } : l));
}
remove(productId: string): void {
this._lines.update(lines => lines.filter(l => l.productId !== productId));
}
clear(): void { this._lines.set([]); }
}
Read what this gives you for one extra line. There are exactly four functions in the entire application that can change a cart. A wrong total has four candidate causes, and each is ten lines long.
That is most of what a Redux store was ever bought for — a bounded, named set of state transitions — without actions, reducers, selectors or a second mental model.
What the Redux pattern actually buys, so you can say when it is worth it
NgRx is not ceremony for its own sake. It buys four specific things, and the honest senior answer names them and then says whether you need them.
- An action log. Every change is a named, serialisable event, so you can replay a user's session and see exactly what happened in order.
- Time-travel debugging. Because state is derived from an ordered list of actions, tooling can step backwards through it.
- A hard boundary between intent and change. Components dispatch intent and never touch state, which scales across teams who do not read each other's code.
- Effects as a declared side-effect layer, so asynchronous work is visible in one place rather than scattered.
The costs are equally concrete: several files per feature, a second mental model for every new joiner, and a strong pull toward putting server data in the store, which is the mistake from the previous section.
So the answer to "should we use NgRx" is: only if you would use the action log. If nobody would ever open the devtools timeline, you are paying for a feature you do not consume.
NgRx SignalStore, if you do escalate
SignalStore is the modern middle rung: the structure of a store with the ergonomics of signals and no actions or reducers.
import { signalStore, withState, withComputed, withMethods, patchState } from '@ngrx/signals';
export const CartStore = signalStore(
{ providedIn: 'root' },
withState({ lines: [] as CartLine[], loading: false }),
withComputed(({ lines }) => ({
count: computed(() => lines().reduce((n, l) => n + l.qty, 0)),
subtotal: computed(() => lines().reduce((s, l) => s + l.qty * l.price, 0)),
})),
withMethods((store) => ({
add(product: Product, qty = 1) {
patchState(store, { lines: mergeLine(store.lines(), product, qty) });
},
remove(productId: string) {
patchState(store, { lines: store.lines().filter(l => l.productId !== productId) });
},
})),
);
// In a component: private readonly cart = inject(CartStore); cart.count()
What it adds over a hand-written service is convention — every store in the codebase has the same shape — plus entity helpers for collections keyed by id, and composable features you can reuse across stores.
What it does not add is a global action log, which is the thing you were escalating for in rung four.
When an interviewer asks "how do you manage state in Angular", they are usually checking two things and neither is library knowledge.
First, do you distinguish server cache from client state, or do you put everything in one bucket? Answering with the four kinds immediately places you above most candidates.
Second, do you escalate on evidence or on habit? "We used NgRx because that is what we always use" and "we used signals in services and never needed more" are both fine outcomes — what is graded is whether you can name the pressure that would change your mind.
Quick reference — State management
- Four kinds of state
- Server cache (owned by the server), URL state (owned by the address bar), local UI state (owned by one component), shared client state (owned by the app).
- The expensive mistake
- Treating server data as client state. You then own cache invalidation and end up hand-rolling a caching library inside your store.
- The ladder
- Component signals → a service with signals → SignalStore → full NgRx. Escalate on evidence, and expect most applications to stay on rung two.
- The rung-two shape
- Private writable signal,
asReadonly()public view, derived values ascomputed, and a small named set of methods that are the only writers. - What NgRx buys
- An action log, time travel, a hard intent/state boundary, and a declared effects layer. Adopt it if you would actually use the log; otherwise you are paying without consuming.
- URL state
- Anything a user would expect to survive a refresh or be shareable by link — filters, sort, page, tab — belongs in query parameters, not in a store.
07 · The primerPerformance & the Bundle — Three Budgets, Measured Not Guessed
Frontend performance splits into three separate budgets: what the user downloads, how long the first render takes, and how much work happens per interaction. They have different causes and different fixes, and conflating them is why optimisation efforts fail.
A senior is expected to diagnose before prescribing. So the first move is always to decide which of the three budgets is actually being spent.
| Budget | Symptom | Measured by | Primary levers |
|---|---|---|---|
| Download | Slow on mobile and on first visit; fine once cached | Bundle size, Largest Contentful Paint | Lazy routes, @defer, tree-shaking, dependency choice |
| Startup | The page appears but does nothing for a second or two | Time to Interactive, Total Blocking Time | Less work at bootstrap, SSR with incremental hydration, deferring third parties |
| Interaction | Typing lags, scrolling stutters, a click takes 300 ms to respond | Interaction to Next Paint, the Angular profiler | Signals and OnPush, track, computed instead of template methods, virtual scrolling |
The download budget
Start by looking rather than guessing. ng build --stats-json plus a bundle analyser renders the output as a treemap, and the biggest rectangle is nearly always a surprise.
The recurring findings, in rough order of frequency:
- A utility library imported as a namespace.
import * as _ from 'lodash'pulls the whole library because a namespace import cannot be tree-shaken.import debounce from 'lodash-es/debounce'pulls one function. - A date library with every locale. Moment was the classic; the modern equivalents are date libraries configured to include all locales when you ship two.
- An icon or component package imported through a barrel file, where one
index.tsre-exports everything and the bundler cannot prove what is unused. - A "shared" module that grew a dependency on a feature, so importing one button drags a chart library into the initial bundle.
- A package with no ES-module build at all, which cannot be tree-shaken by anyone.
The structural levers are lazy routes for whole feature areas, and @defer for heavy things inside a page.
<!-- The chart library is not in the initial bundle at all.
It downloads when this block scrolls into view. -->
@defer (on viewport) {
<app-revenue-chart [data]="series()" />
} @placeholder (minimum 300ms) {
<div class="chart-skeleton" aria-hidden="true"></div>
} @loading (after 100ms; minimum 400ms) {
<p>Loading chart…</p>
} @error {
<p>The chart could not be loaded. <button (click)="retry()">Retry</button></p>
}
Read the timing options, because they are the part people skip. @placeholder (minimum 300ms) stops the placeholder flashing away instantly on a fast connection. @loading (after 100ms; minimum 400ms) stops a spinner appearing at all for a fast load, and stops it flickering when it does.
Those two options are the difference between a defer block that feels smooth and one that feels twitchy, and they cost nothing.
The triggers are on viewport, on interaction, on hover, on idle, on timer(2s), on immediate, and when someSignal(). Each can be paired with a prefetch clause, so the code downloads early but renders late.
Bundle budgets in angular.json make regressions fail the build. Set them just above today's numbers rather than at an aspirational figure, so they catch a change rather than sitting permanently red and being ignored.
The interaction budget
Once the app is loaded, slowness has a small number of causes, and they are checkable in order.
- A method called from a template. No caching, no dependency tracking, runs on every render. Move it to a
computed. - A missing or unstable
track. Every render destroys and rebuilds the whole list. Check this before anything clever. - Too many components on screen. Five hundred rows times four bindings is two thousand comparisons per pass. Virtual scrolling or pagination.
- An impure pipe, which re-runs on every cycle by design.
- Expensive work inside an effect that runs more often than you think, usually because it reads a signal you did not mean to depend on.
untrackedthe incidental reads. - Layout thrashing — reading
offsetHeightand then writing a style, repeatedly, forcing the browser to recompute layout each time. This one is not Angular's fault and the profiler will show it as style and layout, not scripting.
The measurement tools are worth naming precisely, because "I would profile it" is a weak answer and naming the panel is a strong one.
Angular DevTools has a profiler that records change detection cycles and shows a flame chart of time per component, plus how many times each was checked. That answers "which component" and "how often".
Chrome's Performance panel answers "scripting, layout, or paint", which Angular's own tool cannot.
Both should be run against a production build with CPU throttling. A development build on a fast laptop hides the problem that a mid-range phone will find.
Images, which are usually the largest thing on the page
<!-- width and height are REQUIRED: they reserve space and prevent layout shift -->
<img ngSrc="/hero.jpg" width="1200" height="600" priority alt="Product overview">
<!-- Below the fold: no priority, so it lazy-loads by default -->
<img ngSrc="/thumb.jpg" width="240" height="160" alt="Thumbnail">
The directive enforces the things people forget: dimensions to prevent layout shift, lazy loading by default, a preload link for the one image marked priority, and a warning in development when an oversized image is being scaled down in the browser.
Marking exactly one image priority — the one that is the Largest Contentful Paint element — is usually worth more than any JavaScript optimisation on a content-heavy page.
A dashboard renders 200 rows. Each row is an OnPush component with an @Input() object. A background WebSocket updates one row's price every second by mutating the object in place. The developer reports "the row does not update, so I added ChangeDetectionStrategy.Default everywhere and now it works but the page is slow". What actually happened, and what should they have done?
Think first, then open
The mutation kept the object's identity, so the parent's comparison found no change and the child was never marked dirty. That is OnPush behaving exactly as documented.
Switching to the always-check strategy "fixed" it by removing the skip — now every row is re-evaluated on every pass, and since the WebSocket fires once a second under Zone.js, that is 200 components times their bindings, every second. Hence the slowness.
The correct fix is at the data layer, not the strategy: replace instead of mutating. The socket handler updates a signal holding the row list with list.map(r => r.id === id ? { ...r, price } : r).
That changes exactly one row's identity, so exactly one row is marked dirty and re-rendered. The other 199 keep their references, keep their DOM, and cost nothing. The page is now both correct and faster than it was before the bug.
This one scenario contains the whole chapter: mutation versus replacement, what marks a component dirty, and why the tempting fix makes things worse.
Quick reference — Performance
- Three budgets
- Download (bundle, LCP), startup (TTI, blocking time), interaction (INP, profiler). Diagnose which one before optimising.
- Finding bundle bloat
ng build --stats-jsonplus an analyser. Usual causes: namespace imports, all locales, barrel files, a shared module that grew a feature dependency, a package with no ES-module build.@defer- Triggers: viewport, interaction, hover, idle, timer, immediate,
when. Always set@placeholder (minimum …)and@loading (after …; minimum …)or it flickers. - Interaction checklist
- Template method calls, missing
track, too many components, impure pipes, over-triggered effects, layout thrashing — in that order. - Measurement
- Angular DevTools profiler for which component and how often; Chrome Performance panel for scripting versus layout versus paint. Always a production build with CPU throttling.
NgOptimizedImage- Requires width and height, lazy-loads by default, preloads the one image marked
priority, and warns about oversized sources.
08 · The primerSSR, Hydration & the Server — What the User Sees Before Your Code Runs
Server-side rendering means Angular runs on the server and sends real HTML. Hydration is the client-side app adopting that HTML instead of rebuilding it. Both are simple ideas with a specific set of failure modes worth knowing before you turn them on.
A plain client-rendered Angular app sends an almost empty HTML document. The browser downloads it, downloads the JavaScript, executes it, and only then does anything appear.
On a fast connection that is imperceptible. On a mid-range phone on a mobile network it is two to four seconds of blank screen, and for a crawler it may be a blank page permanently.
The sequence, precisely
- The request reaches a Node server running your application.
- Angular renders the component tree for that URL to an HTML string, running your components' constructors and resolving their data.
- The HTML is sent. The user sees content — real text and images, with no JavaScript executed in their browser yet.
- The JavaScript bundle downloads and boots. Hydration begins: Angular walks the existing DOM and claims it, matching each node to the component that would have created it.
- Event listeners are attached. The page becomes interactive.
The gap between step 3 and step 5 is the honest cost of SSR: a page that looks ready and does not respond to clicks. Users notice, and the metric that captures it is Interaction to Next Paint.
Hydration, and why the older version was worse
Before Angular 16, the client did not adopt the server's DOM — it destroyed and re-created it. The visible result was a flicker on every page load, and the whole benefit was partly cancelled.
Full hydration (provideClientHydration()) reuses the nodes. Incremental hydration goes further: combined with @defer, a section stays as inert server-rendered HTML until a trigger fires.
// app.config.ts
provideClientHydration(withIncrementalHydration()),
<!-- Server-rendered and visible immediately. Its JavaScript is neither
downloaded nor executed until the user scrolls to it. -->
@defer (hydrate on viewport) {
<app-reviews [productId]="id()" />
}
This matters because full hydration has to download and execute the JavaScript for the entire page before anything becomes interactive. Incremental hydration reduces that to the parts the user actually reaches.
Transfer state — the double-fetch nobody notices
The server fetched your data to render the page. Without help, the client boots and fetches all of it again — doubling the load on your API and delaying interactivity.
Angular's transfer state serialises the server's HTTP responses into a script tag in the page. On the client, matching requests are answered from that cache instead of going to the network.
It is on by default with provideClientHydration() for HttpClient GET requests, and httpResource participates automatically. You can turn it off per request with a context token when a value must be fresh.
What breaks, and the three-item checklist
SSR failures are systematic, and almost all of them are one of three things.
| Failure | Cause | Fix |
|---|---|---|
window is not defined at render time |
Code touching window, document, localStorage or navigator during construction |
Move it to afterNextRender, which never runs on the server; or guard with isPlatformBrowser |
| Hydration mismatch warnings, and a flicker | The client rendered different markup than the server — usually invalid HTML nesting the browser silently corrected, or a value like Date.now() that differs between the two |
Fix the nesting; make time-dependent and random values stable, or render them only after hydration |
| The server hangs or times out | A never-completing observable or an interval keeping the render alive — the server waits for the app to become stable | Make the stream complete, or exclude it on the server. Timers must be started in afterNextRender |
The third one is the nastiest, because the symptom is a slow endpoint rather than an error, and it usually appears under load rather than in development.
Deciding whether you want any of this
SSR is a product decision with an operational cost, not a default setting.
Turn it on when search ranking matters, when link previews on social platforms matter, when first impression on a slow connection is part of the conversion funnel, or when the content is genuinely public.
Leave it off for an internal tool behind a login. No crawler sees it, users open it once and keep the tab open all day, and you have added a Node process to run, monitor and scale for a benefit measured in one page load per working day.
There is a third option worth naming: prerendering, also called static site generation. Routes that do not depend on the user are rendered at build time into static HTML, which needs no server at all in production. For marketing pages, documentation and public catalogues, it is strictly better than SSR — same first paint, no runtime cost.
Quick reference — SSR and hydration
- The sequence
- Server renders HTML → user sees content → bundle boots → hydration adopts the DOM → listeners attach → interactive. The gap between content and interactive is the real cost.
- Hydration
provideClientHydration()reuses server DOM instead of rebuilding it. Before Angular 16 it rebuilt, which is why old SSR flickered.- Incremental hydration
withIncrementalHydration()plus@defer (hydrate on …). A block stays inert server HTML until its trigger, so the page becomes interactive without executing everything.- Transfer state
- Server HTTP responses are serialised into the page so the client does not refetch. On by default for GETs with hydration enabled.
- Three failure modes
- Browser globals at construction time; hydration mismatch from invalid nesting or unstable values; a never-completing stream keeping the server render from finishing.
afterNextRender- Runs only in the browser, after the render. The correct home for DOM measurement, timers, and third-party widget initialisation.
- Prerendering
- Static HTML at build time for user-independent routes. Same first paint as SSR with no server to run — the right answer for marketing and documentation pages.
09 · DrillReactivity & Rendering — Q1–Q50
Senior Angular rounds do not ask you to write a component. They ask what happens between the moment a value changes and the moment a pixel does.
These fifty questions drill change detection, the signal graph, OnPush, the zoneless model, and the rendering behaviour that produces most stale-screen and slow-page bugs. Every answer names the exact mechanism, because "change detection ran" is a mid-level answer and "the signal marked the view dirty and the ancestors as having a dirty descendant" is a senior one.
Say the answer out loud before you reveal it.
The first ten questions establish the mental model everything else in this block depends on: what a pass does, what starts one, and what it is allowed to skip.
Q1. "Walk me through exactly what Angular does during one change detection pass."
Reveal answer
The real test Whether you know it re-evaluates and compares rather than observing your fields.
Strong answer Angular starts at the root and walks down the component tree. At each component it decides whether it may skip the subtree, and if not, it runs a function the compiler generated for that component's template.
That function has two branches. The create branch runs once and builds the elements. The update branch runs on every check: it evaluates each bound expression, compares the result with the value stored in a slot on the view, and writes to the DOM only when they differ.
So change detection does not detect changes in any observational sense. There is no proxy on your fields and no virtual DOM diff. It re-runs expressions and compares outputs.
That is why a check of an unchanged component is cheap but not free — the expressions still run and the comparisons still happen; only the DOM write is skipped.
Land it Once you say "it re-evaluates and compares", the cost of calling a method from a template becomes obvious rather than a rule you memorised.
- "Where does it store the previous value to compare against?"
In the component's
LView, a flat array Angular keeps per view instance. Each binding gets an index, allocated at compile time, and the previous value lives in that slot.Using a flat array rather than a map is a deliberate performance choice: the index is known statically, so a lookup is an array access rather than a hash.
It also explains why the number of bindings in a template is the unit of cost — each one is a slot, an evaluation and a comparison on every check that is not skipped.
- "Is the comparison
===?" It is
Object.is, which differs from===in exactly two cases:NaNis equal to itself underObject.isbut not under===, and+0and-0are distinct underObject.isbut equal under===.The
NaNbehaviour is the useful one — under===, a binding holdingNaNwould be considered changed on every single pass and would write to the DOM forever.
Q2. "In a zoneless Angular application, what are all the things that can schedule a change detection pass?"
Reveal answer
Strong answer The list is short and knowing it exactly is the point.
- A signal read by a template changes value. The signal notifies its consumers, and a template consumer marks its view dirty.
- A template event handler runs — a
(click), an(input). Angular marks that component dirty after the handler returns. markForCheck()is called, explicitly or by something like theasyncpipe.ApplicationRef.tick()is called directly.- A resource settles, or a route activates — both of which internally do one of the above.
Nothing else causes a render. A setTimeout that assigns a plain field, a WebSocket message handler, a third-party callback — none of them trigger anything, because nothing is patched any more.
The pass is also scheduled rather than immediate, and several triggers within the same task are coalesced into one pass.
Land it The practical rule that falls out is that every piece of state a template reads must be a signal — that is the entire zoneless migration, and it is also just better design.
- "What exactly did Zone.js do that this replaces?"
It monkey-patched the browser's asynchronous APIs at startup —
setTimeout,setInterval,addEventListener, promises,XMLHttpRequest— with wrapped versions that reported when the last task in a batch finished.Angular's only possible response was to check the entire tree, because "something finished" carries no information about what changed.
The costs were about 15 KB of JavaScript, stack traces threaded through zone frames, occasional incompatibility with libraries that also patched those APIs, and idle-CPU burn from any library that polls.
- "How do you make a WebSocket update the screen in a zoneless app?"
Write the message into a signal.
socket.onmessage = e => this.messages.update(m => [...m, parse(e.data)])— setting the signal is what schedules the render, and no zone is involved.If for some reason the value genuinely cannot be a signal,
inject(ChangeDetectorRef).markForCheck()in the handler is the bridge. Every use of that is a note that some state has not been converted yet.
Q3. "Explain markForCheck versus detectChanges versus ApplicationRef.tick."
Reveal answer
Strong answer markForCheck() renders nothing. It sets a dirty flag on this view and walks up marking every ancestor as having a dirty descendant, so the next scheduled pass will reach it rather than skipping the subtree.
detectChanges() runs a check right now, synchronously, on this view and its children. It bypasses the scheduler entirely and does not touch ancestors.
ApplicationRef.tick() runs a full pass from the root of the application, synchronously.
In signal-based code you should need none of them. Reaching for detectChanges() in application code almost always means some state is not in a signal.
Land it Mark flags and lets the scheduler batch; detect forces work now and can produce ExpressionChanged errors in development because it runs outside the normal cycle.
- "Why does marking have to touch the ancestors?"
Because a pass starts at the root and walks down, skipping subtrees it believes are clean. A dirty flag on a leaf would never be seen, since the traversal would stop three levels above it.
So marking is two distinct operations: this view is dirty, and this view has a dirty descendant on each ancestor up to the root. The second is what keeps the path open.
- "When is
detach()and manualdetectChanges()the right tool?" For a component driven by a very high-frequency source that must not drive the framework — a live chart at sixty frames per second, a canvas overlay, a ticker.
You call
cdr.detach()so Angular never checks it, thencdr.detectChanges()yourself at the rate you want, typically inside arequestAnimationFrameloop started inafterNextRender.It is a real technique and a rare one. Reaching for it before profiling is how codebases end up with components nobody can debug, because the normal mental model no longer applies to them.
Q4 · Scenario. "An OnPush component shows stale data after a background update. Give me your diagnosis order."
Reveal answer
Strong answer Four checks, cheapest first.
- Was an object mutated instead of replaced? This is the cause about seventy percent of the time.
task.done = trueon an object passed as an input leaves the reference identical, so the parent's comparison passes and the child is never marked. I look at whoever writes the data, not at the component that displays it. - Is the state in a signal at all? A plain field written by a WebSocket handler or a third-party callback marks nothing. In a zoneless app that is silent.
- Is the value arriving through a manual
subscriberather than theasyncpipe ortoSignal? A bare subscribe assigns a field and does not callmarkForCheck; the pipe does it for you. - Is the component actually the one I think it is? If a parent is also
OnPushand was never marked, the pass never reaches the child regardless of what the child did.
To confirm rather than guess, I put a console.count() in the template via a bound getter, or use the Angular DevTools profiler to see whether the component is being checked at all — that distinguishes "not checked" from "checked and the value really is the same".
Land it The distinction that shortens the debugging is not checked versus checked but unchanged: the first is a marking problem, the second is a data problem, and they have nothing in common.
- "Why does the
asyncpipe work withOnPushwhen a manual subscribe does not?" Because the pipe calls
markForCheck()itself every time the observable emits. That is essentially its whole implementation beyond subscribing and unsubscribing.A manual
subscribethat assignsthis.value = vdoes nothing to the change detector, so anOnPushcomponent keeps rendering the previous value until something else happens to mark it — which is why the bug is intermittent and looks haunted.toSignalsolves it more cleanly, because reading the signal in the template creates the dependency and the notification path directly.- "The team's fix was to switch that component back to the eager strategy. What do you say?"
That it treats the symptom and makes the page slower, because the component is now re-evaluated on every pass in the whole application rather than only when its data changes.
It also leaves the real defect in place: something is mutating shared data, and every other consumer of that object has the same bug waiting.
I would fix the write to replace instead of mutate, which fixes every consumer at once and keeps the skip.
Q5. "What is ExpressionChangedAfterItHasBeenCheckedError really telling you?"
Reveal answer
Strong answer In development mode Angular runs each pass twice and compares. The error says a binding produced a different value on the second run, which means the DOM it just shipped does not match the state the application now holds.
That is a genuine bug, not a framework annoyance: the rendered value and the real value disagree, and which one the user sees becomes timing-dependent.
Three causes cover nearly all cases. A child writing to a parent's state after the parent has rendered, typically from ngAfterViewInit. A template expression that returns a new object or array on each call, so the two passes see different identities. And a lifecycle hook setting state that the same pass already rendered.
The fixes are respectively: move the write into an event, hoist the expression into a computed so the identity is stable, and use afterNextRender which runs after the pass rather than inside it.
Land it Wrapping the write in setTimeout silences it by pushing the change into the next task — the user then sees one frame of the wrong value, and you have converted a loud bug into a quiet one.
- "Why does it not happen in production?"
The verification pass only runs in development mode, because running every pass twice would roughly double change detection cost for no user benefit.
The underlying inconsistency still happens in production — it is simply not reported. That is the argument for never suppressing the error: production is where it becomes an intermittent visual bug that nobody can reproduce.
- "Do signals make this go away?"
Largely, because the common causes disappear. A
computedhas a stable identity between the two passes, and derived state cannot be written to at the wrong moment because it cannot be written to at all.It is still reachable — an effect or a lifecycle hook that writes a signal the same pass already rendered will do it — but the shape of code that produces it becomes unusual rather than routine.
Q6. "Why is calling a method from a template expensive, and exactly how expensive?"
Reveal answer
Strong answer Because the update branch of the generated template function runs on every check that is not skipped, and a method call has no caching and no dependency tracking. Angular cannot know whether the result could have changed, so it calls it again.
The cost is the method's own cost multiplied by the number of checks. Under Zone.js on a busy page that could be dozens per second; in a zoneless app it is once per relevant change, which is much better but still once per render rather than once per data change.
There is a second, worse effect. If the method returns a new array or object each call, the comparison always fails, so the DOM is written every time — and any OnPush child receiving it is marked dirty every time, defeating the skip for a whole subtree.
A computed fixes both: it runs once per genuine dependency change, and its cached result keeps a stable identity in between.
Land it The identity point is the one people miss — a template method that builds an array is not just slow, it silently disables OnPush for everything downstream of it.
- "Is a getter any better than a method?"
No. A getter is a function call with different syntax, and Angular evaluates it on exactly the same schedule. It is slightly worse in practice, because it looks like a property and so reviewers do not question its cost.
The same applies to a pipe that is impure, which re-runs on every cycle by design.
- "What about a pure pipe?"
A pure pipe is genuinely cheaper: Angular caches the result and only re-invokes it when the input reference changes, so it behaves much like a small
computedscoped to that binding.The remaining difference is testability and reuse. A
computedlives in the class where it can be unit-tested without rendering, while a pipe is reusable across templates. For formatting, a pure pipe is right; for filtering or sorting a collection, acomputedis right, which is why Angular deliberately ships no filter or orderBy pipe.
Q7. "What happens, step by step, when you call set on a signal that five computeds depend on?"
Reveal answer
Strong answer First Angular compares the new value with the current one using Object.is, or a custom equal function if one was supplied. If they are equal, nothing happens at all — no version bump, no notification.
If they differ, the signal increments its version number and walks its consumer list, marking each consumer "maybe dirty". It then walks their consumers and marks those too, transitively.
No computed function runs. The entire operation is flag-setting, so five dependent computeds cost five flag writes and zero calculations.
The work happens on the next read. A computed that is read sees it is maybe dirty, asks each of its producers for their current version, and re-runs only if some version differs from the one it recorded. If everything matches, it returns its cached value without executing.
Land it Push the rumour, pull the value — that split is what makes an expensive derivation on a screen nobody is looking at cost literally nothing.
- "Why keep version numbers if you already have dirty flags?"
Because "maybe dirty" propagates transitively and is often wrong. Consider A → B → C: setting A marks B and C maybe dirty. But B might recompute to the same value, in which case C has no reason to run.
Versions let C detect exactly that: B's version did not increment, so C returns its cache. Without versions, C would recompute every time anything upstream twitched, and the invalidation would cascade further than the actual change.
- "What is the difference between 'maybe dirty' and 'dirty'?"
Dirty means a direct producer definitely changed, so a recompute is certain. Maybe dirty means something further upstream changed, so a recompute may or may not be needed.
On a read, a maybe-dirty node resolves the question by checking its producers' versions, which may involve recursively resolving them first. That recursive check is exactly what makes the graph glitch-free.
Q8. "What does it mean that Angular's signal graph is glitch-free? Give the diamond example."
Reveal answer
The real test Whether you can name a value the system guarantees is never observable.
Strong answer Glitch-free means a consumer can never observe a half-updated world — a combination of producer values that does not correspond to any consistent state of the inputs.
The diamond: width is a signal, height = computed(() => width() * 2), and area = computed(() => width() * height()). So area depends on width both directly and through height.
With width at 10, height is 20 and area is 200. Set width to 20. A naive push-based system might recompute area immediately while height still holds 20, producing 400 — a value that is wrong for both the old and the new state.
Angular cannot produce it, because the push computes nothing. When area is finally read, it asks height for its value, height notices it is stale and recomputes to 40, and area returns 800.
Land it The intermediate 400 does not exist at any instant, which is precisely the guarantee that a chain of manual update callbacks cannot give you.
- "Does the same guarantee hold for effects?"
Yes, and it is the reason effects are queued rather than run synchronously. An effect reading both
heightandarearuns once, after the whole change has settled, and sees a consistent pair.If effects ran synchronously on each producer's change, an effect would fire once per producer and could observe exactly the inconsistent intermediate the graph works to avoid.
Q9. "A computed reads a signal inside an if branch that is not currently taken. Is that signal a dependency?"
Reveal answer
Strong answer No. Dependencies are recorded from the reads that actually happened during the last execution, and they are rebuilt from scratch on every execution.
So with computed(() => useMetric() ? celsius() : fahrenheit()), while useMetric is true the dependencies are useMetric and celsius. Setting fahrenheit does nothing at all — not a wasted recompute, not even a flag.
When useMetric flips, the computed is invalidated because useMetric is a dependency. It re-runs, takes the other branch, and its dependency set becomes useMetric and fahrenheit. celsius is dropped and can no longer invalidate it.
Land it Dynamic tracking is what makes conditional derivations cheap, and it is also a trap — an early return can silently stop tracking something, and the symptom is "this value updates sometimes".
- "How would you deliberately force a dependency you do not use the value of?"
Read it and discard the result — a bare
this.refreshToken();statement before the rest of the function. The read is what registers the dependency, not what you do with the value.That is exactly the shape of the
linkedSignalreset pattern: read the source to declare "I depend on this", then return a fresh default.It needs a comment, because a linter or a reviewer will see a pointless expression statement and want to delete it.
- "Does the same dynamic tracking apply to templates?"
Yes, and it is one of the quiet wins of the built-in control flow. A signal read only inside an
@ifblock that is false is not a dependency of that view while the block is not rendered, so changing it does not mark the component dirty.The old
*ngIfbehaved similarly for the embedded view, but the modern control flow makes the boundaries clearer to the compiler and to the reader.
Q10. "When does an effect run, and why is it not synchronous?"
Reveal answer
Strong answer An effect runs once when it is created, and then again whenever any signal it read changes — but not at the moment of the change. It is queued and executed as part of the change detection cycle, after the DOM has been updated.
It is not synchronous for two reasons. Consistency: running it immediately on each producer change would let it observe the half-updated intermediate state the graph works to prevent. And efficiency: several changes in one task coalesce into a single execution rather than one per set.
Its cleanup callback runs before each subsequent execution and once more when the effect is destroyed, which is how you cancel the previous piece of work.
Land it The coalescing is the practical fact: setting four signals in one function queues the effect once, which is usually what you want and occasionally what confuses you when counting log lines.
- "Show me the cleanup pattern."
The effect's function receives an
onCleanupregistration callback. A typical use is a subscription keyed by a signal:effect((onCleanup) => { const s = new WebSocket(url(this.roomId())); onCleanup(() => s.close()); });Without it, switching rooms five times leaves five open sockets all writing into the same list. It is the signal-era version of the subscription leak, and it is easy to miss because effects otherwise clean themselves up.
- "When should you use
afterNextRenderinstead of an effect?" When the work is about the DOM rather than about data.
afterNextRenderruns once, in the browser only, after the render completes — so it is the right home for measuring an element, initialising a third-party widget, or starting an animation loop.Crucially it does not run during server-side rendering, which an effect does. Putting
documentaccess in an effect is a common way to break SSR while everything works locally.
These questions move from the mechanism to the decisions: which primitive, what breaks, and how you would explain the failure to a colleague.
Q11. "When is computed wrong and linkedSignal right?"
Reveal answer
Strong answer When the value must be writable by the user and reset when something upstream changes. A computed is read-only, so it cannot cover the first half.
The canonical case is a quantity input on a product page: the user types 5, so it is writable; they switch product, and it must return to 1.
linkedSignal(() => { this.selectedProduct(); return 1; }) does both. The bare read of selectedProduct declares the dependency; the return value is the reset.
Before it existed this needed an effect that wrote to a signal — the pattern Angular explicitly discourages, because it runs late and can loop.
Land it Whenever you catch yourself writing an effect whose only job is to reset a field, stop: that is linkedSignal.
- "Give two more examples from real screens."
A selected table row that must clear when the filter changes, because the selected row may no longer be in the list and a hidden selection is how bulk-action accidents happen.
A paginator's current page, writable when the user pages and reset to 1 when the search term changes. Both have the same shape: user-owned, invalidated by an upstream change.
- "Can
linkedSignalsee its own previous value?" Yes, with the source-and-computation form: you give it a
sourcesignal and a computation that receives both the new source value and the previous state. That lets you write "keep the selection if it still exists in the new list, otherwise clear it", which is often the behaviour users actually want.
Q12. "Why does Angular warn about writing to signals inside effects?"
Reveal answer
Strong answer Because it is almost always a computed written the hard way, and it has three concrete failure modes.
It runs late: the effect executes after the render, so there is a window in which the derived value is stale and may already have been displayed.
It can loop: if the effect reads a signal that its own write invalidates, it re-queues itself indefinitely.
And it hides the dependency: a reader of the code sees a value being assigned somewhere unrelated instead of a declared relationship, so "why is this 7" becomes a search.
The legitimate uses are narrow — bridging from a non-reactive source, and cases now covered by linkedSignal or resource.
Land it The test is simple: if the effect's last statement is a set, delete the effect and write a computed.
- "What is a case where writing from an effect genuinely is correct?"
Bridging an external event source that Angular knows nothing about — a WebSocket, a browser event you subscribed to yourself, a third-party widget's callback. The effect sets up the subscription, and the handler writes a signal.
Note that the write there happens in the handler, not in the effect body, so it is not really the discouraged pattern. The discouraged one is reading signal A in the body and immediately setting signal B from it.
Q13. "What does untracked do and when have you needed it?"
Reveal answer
Strong answer It reads a signal's current value without registering a dependency, so the read cannot cause the surrounding computed or effect to re-run.
The case I hit most is analytics. An effect should fire when the selection changes, and the log line also wants the current user — but a change of user is not a selection event and should not send a duplicate.
So the selection is read normally and the user is read inside untracked(() => this.currentUser()).
The general rule is: track the things that should cause the work; untrack the things you merely need the value of.
Land it An effect that fires more often than the user did anything is nearly always an incidental read that should have been untracked.
- "Can it be used to break an infinite effect loop?"
It can, and that is a warning sign rather than a solution. If an effect reads X, writes Y, and reading Y is what re-triggers it, untracking the read stops the loop.
But the underlying design is still a derivation expressed as a side effect. I would use
untrackedto stop the bleeding and then convert the whole thing to acomputedor alinkedSignal.
Q14 · Scenario. "A colleague says signals made their page slower. What could they have done?"
Reveal answer
Strong answer Three things produce that outcome, and all of them are misuse rather than signals being slow.
A computed that returns a new object or array every time. Downstream consumers compare by identity, so everything is invalidated on every recompute. The whole caching benefit is cancelled, and every OnPush child receiving it is marked dirty.
Signals holding coarse state. One signal holding a whole page's view model means any field changing invalidates every consumer of any field. Splitting into several signals, or deriving fine-grained computeds, restores the precision.
Effects doing work that should be derived. An effect that recalculates and writes runs after the render and can cascade, where a computed would have run once, lazily, and been cached.
I would confirm with the Angular DevTools profiler, which shows how often each component is actually checked — that separates "signals are slow" from "everything is being invalidated".
Land it Signals make invalidation precise; if the page got slower, something is invalidating more than it should, and the profiler names it in about a minute.
- "How would you fix a computed that must return a new object?"
First ask whether it must. Often it is building a view model that could be several separate computeds, each with a primitive value that compares cheaply.
If a new object really is the right shape, pass a custom
equalfunction that compares the fields that matter, so downstream consumers are not invalidated by an equivalent rebuild.That is a sharp tool: an equality function that reports "equal" when something did change produces a silently stale screen, which is far harder to diagnose than the performance problem it replaced.
Q15. "What exactly is a signal input, and how does it differ from @Input() at runtime?"
Reveal answer
Strong answer A signal input is a read-only signal whose value is written by the framework when the parent's binding is evaluated. Reading it in a template or a computed creates a dependency exactly like any other signal.
The runtime differences that matter are three. Reacting to a change is a computed rather than ngOnChanges, so there is no string-keyed SimpleChanges object and no manual previous-versus-current comparison.
Required-ness is enforced by the compiler with input.required(), where the decorator form needed a non-null assertion and a hope.
And the value participates in the graph, so a component whose template reads only signal inputs is marked dirty precisely when one of them changes — the input write itself is the notification.
Land it The migration hazard is that ngOnChanges does not fire for signal inputs, so a half-converted component can have a hook that quietly stops covering some of its inputs.
- "What is
model()and when is it appropriate?" A writable signal that is bound two ways: the parent writes it through
[(value)]and the child can write it too, with changes propagating back.It is right for form-like widgets — a rating control, a custom date picker, a search box — where "the parent owns a value and the child edits it" is the honest description.
It is wrong as a general shortcut, because it reintroduces two writers for one piece of state and gives back the debugging cost that unidirectional flow was buying.
- "How do input transforms work?"
input(false, { transform: booleanAttribute })runs the function on whatever the parent passed before storing it.booleanAttributeturns the empty string and"true"intotrue, so<app-x disabled />behaves like native HTML.numberAttributedoes the same for numeric strings. Without them, presence-only attributes pass the empty string, which is falsy, and the flag silently never turns on.
Q16. "What are signal queries, and what problem do they solve?"
Reveal answer
Strong answer viewChild, viewChildren, contentChild and contentChildren return signals holding the queried elements or component instances.
The problem they solve is timing. With the decorator versions, the field was undefined until a particular lifecycle hook fired, so every use had to know which hook and had to be written after it — and a query result changing later, because an @if revealed the element, was invisible.
As signals they simply have a value or not, and reading them in a computed or an effect re-runs when the result changes. There is no hook to know about.
viewChild.required asserts the element always exists and throws with a clear message if it does not, replacing a non-null assertion.
Land it The pattern across inputs, queries and outputs is one idea: lifecycle hooks are being replaced by reactivity, so you declare a relationship instead of being told to go and look.
- "Difference between view queries and content queries?"
A view query searches what this component's own template rendered. A content query searches what a caller projected into it through
<ng-content>.A tab group uses
contentChildrento find the tabs the caller wrote inside it; a component that needs its own canvas element usesviewChild.They also differ in ownership: projected content is created in the parent's context, so its expressions resolve against the parent's class, not the child's.
Q17. "How do resource, rxResource and httpResource differ, and what do they give you?"
Reveal answer
Strong answer All three model an asynchronous value as a set of signals: value, isLoading, error, status, plus reload(). All three became stable in Angular 22.
resource is the general form and takes any async function returning a promise. rxResource takes a function returning an observable, which is the bridge for existing RxJS services. httpResource is the HTTP-specific one: you return a URL or a request object and it does the call.
What they give you beyond convenience is two things worth naming. The request re-runs automatically when any signal read while building it changes — the dependency is the wiring, so there is no code connecting a filter to a fetch.
And the previous request is cancelled when the inputs change again, so an out-of-order response cannot overwrite a newer one.
Land it The cancellation is the correctness feature and debouncing is only the efficiency one — a resource is race-free even if the user types fast.
- "What is the difference between
'loading'and'reloading'instatus()?" 'loading'means there is no previous value — a first load, so the screen has nothing to show.'reloading'means a request is in flight but a previous value is still available.That distinction is what lets you build a table that keeps showing the old rows with a subtle progress bar instead of flashing empty on every keystroke, which is the difference between a smooth filter and a twitchy one.
- "How do you do dependent requests — B needs A's result?"
The natural way is to have B's request function read A's
value()signal, and returnundefinedwhile it is not yet available, which leaves B idle. When A resolves, B's dependency changes and it fires.Angular 22 also added
chain()support for exactly this shape, so the sequencing is expressed once rather than reconstructed from guards.What I would avoid is an effect that watches A and imperatively triggers B — that reintroduces the ordering bug the dependency graph removes.
Q18 · Scenario. "A search box hits the API on every keystroke and results sometimes arrive in the wrong order. Fix it two ways."
Reveal answer
Strong answer There are two separate defects here and it is worth separating them, because they have different fixes.
Too many requests is an efficiency problem, fixed by debouncing — waiting for a pause in typing before firing.
Out-of-order results is a correctness problem, fixed by cancellation — abandoning the previous request when a new one starts.
The signal answer: read a debounced(this.query, 250) signal inside an httpResource's URL function. The debounce solves the first, and the resource's automatic cancellation solves the second.
The RxJS answer: valueChanges.pipe(debounceTime(250), distinctUntilChanged(), switchMap(q => this.api.search(q))). switchMap is the cancellation.
Using mergeMap instead of switchMap is precisely the bug described: both requests run, the earlier and slower one lands last, and the box shows results for a prefix the user already deleted.
Land it Debouncing alone does not fix ordering — a slow request fired 250 ms ago can still land after a fast one fired now.
- "Why
distinctUntilChangedas well?" Because
valueChangesemits on events that do not change the text — pressing an arrow key, or a programmaticsetValuewith the same string. Without it, each of those fires a request for a query that is already displayed.With signals you get this free, since setting a signal to an equal value is a no-op.
- "Does cancelling actually stop the server work?"
Not necessarily. Unsubscribing aborts the browser's request, and with the fetch backend that sends an abort signal — many servers and proxies notice and stop, but a server that has already started an expensive query will usually finish it.
So cancellation guarantees the client ignores the stale response, which is what fixes the ordering bug. If server load is the concern, debouncing and a minimum query length do more than cancellation.
Q19. "Why is toObservable not a lossless event stream?"
Reveal answer
Strong answer Because it emits on the effect timing, not on each set. Signals model state, and several writes within one task collapse into one notification.
So setting a signal to 1, then 2, then 3 inside one function produces a single emission of 3. If you expected three values you have modelled an event sequence as state.
It also does not emit when a write produces an equal value, since the signal itself treats that as a no-op.
For a genuine event stream — "the user clicked save", which can happen three times with the same payload — the right tool is a Subject, because each call to next is a distinct occurrence.
Land it Signals answer "what is the value now"; subjects answer "what happened, in order" — and choosing the wrong one silently drops repeats.
- "And what does
toSignallose in the other direction?" The same thing, plus completion and error semantics. A signal has no notion of "the stream ended", so completion is invisible, and by default an error thrown by the source is re-thrown on read.
Two options matter:
initialValueavoids the type includingundefined, andrequireSync: trueasserts the source emits synchronously on subscribe — which is true for aBehaviorSubjectand false for an HTTP call, where it throws at construction.
Q20. "Two components must react to the same value. When does that belong in a shared signal, and when should the value be passed down?"
Reveal answer
Strong answer Pass it down as an input when the two components are close in the tree and the parent already has the value — one or two levels. That keeps the component reusable, because it depends on a prop rather than on a service that must exist.
Move it to a shared signal in a service when threading it down would cross three or more layers that do not care about it, or when the components are in genuinely different parts of the tree.
The cost of the service is testability and reuse: the component now cannot be rendered without that service, and a second instance of the screen would share the state whether you wanted that or not.
The cost of threading is prop drilling — intermediate components carrying a value only to hand it on, and every one of them needing a change when the shape changes.
Land it My default is inputs for presentational components and a service for anything the whole feature agrees on, and I would rather refactor from inputs to a service than the other way.
- "Is injecting a store directly into a leaf component acceptable?"
It is a real trade rather than a rule. Injecting the store makes the component convenient inside this app and useless outside it, and it makes tests need the store.
My working split is that container components — the ones a route points at — inject stores freely, and presentational components take inputs and emit outputs. That keeps the reusable half reusable and confines the coupling to a thin layer.
Where I bend it is for genuinely ambient state that every component may need, such as the current user or a theme, where threading it everywhere would be worse than the coupling.
What the compiler does with your template, and the rendering behaviour that produces flicker, lost focus and mysterious re-mounts.
Q21. "What does the Angular compiler actually produce from a template?"
Reveal answer
Strong answer A JavaScript function attached to the component class as a static property, with two branches selected by a flags argument.
The create branch runs once and issues instructions that build elements, text nodes and listeners. The update branch runs on every check and issues instructions that evaluate expressions, compare against stored slots, and write the DOM on a difference.
This is ahead-of-time compilation: it happens during ng build, not in the browser. That is why there is no template parser in your bundle and why a typo in a template is a build error rather than a runtime one.
It is also why strictTemplates can type-check bindings — by that point the template is TypeScript, and the compiler can check it like any other code.
Land it Knowing the output is a function with a create branch and an update branch explains the whole cost model: creation is once, evaluation is per check.
- "What was JIT compilation and why did it go?"
Just-in-time compilation shipped the Angular compiler to the browser and parsed templates at startup. It made development builds simpler at the cost of a much larger bundle and slower boot.
Ahead-of-time became the default in Angular 9 with Ivy and is now the only supported mode for applications. The visible consequences are smaller bundles, faster startup, and template errors surfacing at build time.
- "What is
strictTemplatesand why would someone turn it off?" It type-checks template expressions with the same rigour as your TypeScript: binding a string to a
Taskinput, calling a method that does not exist, or reading a possibly-undefined property all fail the build.People turn it off to make a migration compile, and it is an expensive shortcut because it disables checking for every template in the project rather than the awkward ones. The better move is
// @ts-ignore-style local suppressions or fixing the handful of files, so the rest of the codebase keeps its safety net.
Q22. "A user reports that typing in a table's inline edit field loses focus after each character. What is happening?"
Reveal answer
The real test Whether you connect a user-visible symptom to list identity without being prompted.
Strong answer The @for loop's track expression is producing a different value for the same row on each render, so Angular believes every row is a new row.
It destroys the existing DOM and creates fresh elements. The focused input no longer exists, so focus falls back to the document body and the next character goes nowhere.
The usual causes are tracking by something derived from the edited value itself, tracking by an object that is rebuilt each render, or tracking by index in a list that is being re-sorted as you type.
I would confirm by watching the elements panel: if the row's DOM node is replaced rather than updated on each keystroke, that is the whole answer.
The fix is to track by a stable identifier that does not change while editing — a database id, or a client-generated id assigned when the row was created.
Land it Lost focus, reset scroll, restarted animations and cleared checkboxes are all the same bug wearing different clothes: the framework cannot recognise the row.
- "The rows come from an API with no id. What now?"
Assign one on arrival. When the response is mapped into the model, attach a client-side identifier — a counter or a UUID — and track by that.
Tracking by a composite of natural fields is a second-best option and it is fragile, because any field in the composite becoming editable reintroduces the bug.
I would also raise it with the API owner, because a collection endpoint without stable identifiers causes the same problem in every client that consumes it.
- "When is tracking by index actually correct?"
When items have no identity of their own and the list never reorders — a fixed set of form rows the user appends to, or a static list of strings.
Even then, deleting from the middle shifts every subsequent index, so every row after the deletion is considered changed. It is acceptable for append-only lists and wrong for anything that can be sorted, filtered or deleted from.
Q23. "Explain @defer fully — triggers, blocks, and what it does to the bundle."
Reveal answer
Strong answer @defer wraps part of a template and tells the build tool to put everything used only inside that block into a separate chunk, downloaded when a trigger fires.
The triggers are on idle (the default), on viewport, on interaction, on hover, on timer(2s), on immediate, and when someSignal() for a custom condition. Each can be paired with a prefetch clause so the code downloads early but renders late.
There are four blocks: the deferred content, @placeholder shown before the trigger, @loading shown while the chunk downloads, and @error if it fails.
The timing options matter as much as the trigger: @placeholder (minimum 300ms) stops the placeholder flashing away, and @loading (after 100ms; minimum 400ms) stops a spinner appearing at all on a fast connection.
Land it It is the highest ratio of benefit to effort in modern Angular, because the things that dominate a bundle — charts, editors, maps — are usually below the fold anyway.
- "What prevents a component from being deferred?"
Being referenced from anywhere outside the defer block. If the same component is used eagerly elsewhere in the template, or imported in a way that puts it in the main chunk, the code is already there and deferring gains nothing.
The build reports this, and the practical check is to look at the emitted chunks rather than assume. A defer block that produced no separate chunk is decoration.
- "How does this interact with SSR?"
With incremental hydration enabled,
@defer (hydrate on viewport)renders the content on the server so it is visible immediately, but does not download or execute its JavaScript until the trigger fires.That is a genuinely different behaviour from plain
@defer, which would show the placeholder on the server. For content that should be indexed and visible, the hydrate form is the one you want.
Q24. "What is view encapsulation, what are the modes, and what breaks when you change them?"
Reveal answer
Strong answer Encapsulation scopes a component's CSS so its selectors only match its own elements. The default mode, Emulated, does it by adding a generated attribute to every element the component rendered and rewriting the selectors to require it.
ShadowDom uses the browser's real shadow DOM, which gives true isolation — including from global styles, which is usually the surprise. A design system's base stylesheet stops applying inside the component.
None turns it off, and the component's CSS becomes global from the moment that component is first rendered. That is a genuine hazard, because the styles appear when the component loads and stay after it is destroyed.
The consequence of emulated encapsulation is that a parent cannot style into a child. ::ng-deep pierces it but leaks globally unless scoped to something the component owns, and it is deprecated.
Land it The right answer to "I need to style a child" is nearly always an input on the child or a CSS custom property, which passes through encapsulation because it is an inherited value rather than a selector.
- "Why do CSS custom properties cross the boundary when selectors do not?"
Because encapsulation works by rewriting selectors, and a custom property is not a selector — it is an inherited value that cascades down the DOM tree like
colororfont-size.So a parent sets
--card-padding: 1.5remand the child's own stylesheet readspadding: var(--card-padding, 1rem). The child publishes an explicit set of variables it honours, which is a contract rather than a reach-in.This also survives shadow DOM, which is why component libraries theme this way.
- "When is
ShadowDomthe right choice?" When your component will be embedded in pages you do not control — a widget on a customer's site, or a micro-frontend hosted by another team's application. There, isolation from their styles is the point.
Inside a normal application it usually costs more than it gives: global resets and design-system styles stop applying, font loading needs care, and some third-party libraries that query the document cannot find your elements.
Q25. "How does content projection work, and when is projected content created?"
Reveal answer
Strong answer <ng-content> marks a slot where markup written by the caller is inserted. A select attribute takes a CSS selector to create named slots; an unmatched child falls into the plain slot.
The important detail is that projected content is created by the parent, in the parent's context, and then moved into the child's view. Two consequences follow.
Expressions inside projected content resolve against the parent's class, not the child's — so a caller cannot read the child's fields there.
And the content is created even if the child never renders that <ng-content>. Wrapping it in a false @if hides it but does not avoid constructing it, so expensive projected content is still paid for.
Land it If the content is expensive and conditionally shown, take an ng-template and render it with ngTemplateOutlet — that really is lazy, where projection is not.
- "How do you pass data from the child to the projected content?"
Not with
ng-content, which has no mechanism for it. You take anng-templateinstead and render it with a context object:<ng-container *ngTemplateOutlet="rowTpl; context: { $implicit: row, index: i }" />.The caller then writes
<ng-template #rowTpl let-row let-i="index">. That is how every table and list library lets you supply a custom row renderer.
Q26. "What is the difference between ng-container, ng-template and ng-content?"
Reveal answer
Strong answer <ng-container> is a grouping element that produces no DOM node. You use it when you need to apply a directive or wrap several elements without adding a wrapper that would break a CSS grid or a table's structure.
<ng-template> is markup that is not rendered until something renders it. It is the underlying mechanism for the old structural directives, and you use it directly to pass a renderer to a component.
<ng-content> is a projection slot: it does not define markup, it marks where the caller's markup goes.
The one-line distinction: container groups without a node, template defines without rendering, content receives from outside.
Land it ng-container is the one that fixes real layout bugs, because a stray <div> inside a flex or grid container changes the layout in ways that are hard to trace.
- "Do you still need
ng-containernow that@ifexists?" Less often, because the built-in control flow adds no element of its own — that was one of its main motivations, since
*ngIfon a wrapper meant either an extra node or an awkward container.It still earns its place for grouping under a directive that is not control flow, and for
ngTemplateOutlet, which needs a host element that leaves no trace.
Q27 · Scenario. "After a route change, the previous page's component keeps logging. What is going on?"
Reveal answer
Strong answer The component was destroyed but something still holds a reference and keeps calling into it. Almost always a subscription that was never ended.
The likely sources, in order: a subscription to something that never completes — router events, interval, fromEvent, form valueChanges, a WebSocket; a listener added with addEventListener and never removed; or a long-lived root service holding a callback the component passed it.
I would confirm rather than guess: take a heap snapshot, navigate away and back ten times, force garbage collection, take a second snapshot and compare. A component class with a growing instance count names the culprit directly.
The fix is takeUntilDestroyed() at the point of subscription, or inject(DestroyRef).onDestroy(...) for anything that is not an observable.
Land it The snapshot comparison is what turns "probably the subscriptions" into a component name and a count, and it takes two minutes.
- "Why is
takeUntilDestroyedbetter than the olddestroy$pattern?" Because the cleanup is written at the point of subscription rather than in a distant
ngOnDestroy. Nobody has to remember to update a separate method when they add a fourth subscription six months later.It also removes the boilerplate subject and its
next-and-completepair, which people routinely got half-right by callingnextwithoutcomplete.- "Can effects and resources leak the same way?"
Not when created in an injection context — they are tied to the component's
DestroyRefand torn down with it.An effect created with an explicit injector outside that lifetime will keep running, and so will anything the effect started that has no
onCleanup. A WebSocket opened in an effect body without a cleanup callback is a leak per execution, not just per component.
Q28. "What is the CDK, and what would you use it for?"
Reveal answer
Strong answer The Component Dev Kit is Angular Material's foundation, published separately and usable without any Material styles. It provides behaviour, not appearance.
The parts I reach for are the overlay system for dialogs, tooltips and menus, which handles positioning, scroll strategies and the backdrop; the accessibility utilities — focus trap, focus monitor, LiveAnnouncer for screen-reader announcements, and list key manager for arrow-key navigation; virtual scrolling; drag and drop; and layout breakpoint observers.
The reason to use it rather than hand-rolling is that each of those has a long tail of correctness that is invisible until someone uses a keyboard or a screen reader — focus restoration, escape handling, aria wiring, positioning when the viewport is too small.
Land it Using the CDK without Material is the sweet spot for a team with its own design system: you own every pixel and inherit the behaviour that takes a year to get right.
- "What does virtual scrolling cost?"
Rows need a known or measurable height, browser find-in-page only sees rendered rows, deep-linking to an item in the middle needs extra work, and screen readers see a changing set of nodes so the accessibility wiring has to be deliberate.
So it is right for thousands of rows and over-engineered for a hundred, where pagination or simply rendering less per row is cheaper to build and easier to keep correct.
Q29. "How does Angular's renderer relate to the DOM, and why is that indirection there?"
Reveal answer
Strong answer Angular's generated instructions do not call DOM methods directly; they go through a renderer abstraction. In a browser that renderer is a thin wrapper over the real DOM.
The indirection exists for three reasons. Server-side rendering needs a renderer that builds a string rather than touching a document that does not exist. Testing benefits from a substitutable target. And it leaves room for non-DOM targets — historically Angular ran against web workers and native mobile renderers.
The practical consequence for you is that reaching for nativeElement directly bypasses this, which is exactly why such code breaks under SSR and why it is the recommended escape hatch rather than the default.
Land it The rule that follows is to bind values rather than write markup, and to confine unavoidable DOM work to afterNextRender, which never runs on the server.
- "Is writing
nativeElement.innerHTMLever acceptable?" Almost never, and it is a security question rather than a style one. It bypasses Angular's sanitisation entirely, so any user-influenced string in it is a cross-site-scripting hole.
If markup genuinely must be rendered, bind to
[innerHTML], which is sanitised — Angular strips script tags, event-handler attributes andjavascript:URLs. If the source is trusted and Angular cannot know that,bypassSecurityTrustHtmlis the explicit, greppable way to say so.
Q30. "What is the difference between a component and a directive, and when would you write a directive?"
Reveal answer
Strong answer A component is a directive that has a template. That is the literal relationship — @Component extends @Directive with a view.
So a directive adds behaviour to an element that already exists, without owning what it renders. An attribute directive adds behaviour to any host; a structural directive controls whether and how often a template is instantiated.
I write a directive when the same behaviour needs to attach to many different elements — an autofocus, a permission check that hides content, a tooltip trigger, an analytics click tracker, an infinite-scroll sentinel.
The test is whether I am adding markup or adding behaviour. Adding markup is a component; adding behaviour to someone else's markup is a directive.
Land it Directives are the reuse mechanism people under-use, because a component forces a wrapper element and a directive does not.
- "What is
hostDirectives?" A way to compose directives into a component without the caller having to apply them. A component declares
hostDirectives: [CdkOverlayOrigin, TooltipDirective]and behaves as if those were on its host element.It is composition over inheritance for directives: instead of a base class chain, a component assembles the behaviours it wants, and inputs can be exposed or renamed selectively.
- "Why would you write a custom structural directive now that
@ifexists?" For conditions that are not about a boolean in the template — a
*hasPermission="'admin'"directive that consults a service, or a*repeatUntilthat has its own logic.The built-in control flow replaced the three common cases; the extension mechanism is still there and still uses
TemplateRefandViewContainerRef, which is worth being able to explain because it is what@ifcompiles down to conceptually.
The questions that separate people who read the release notes from people who have moved a real codebase.
Q31 · Scenario. "You enable zoneless on a mature application and three screens stop updating. How do you find and fix them?"
Reveal answer
Strong answer Every failure has the same shape: state that a template reads is not in a signal, and nothing marks the component.
I would look for four patterns. A setTimeout or setInterval callback assigning a plain field. A third-party library's callback doing the same — chart onSelect, map onMove, editor onChange. A WebSocket or EventSource handler. And a bare .subscribe() that assigns a field instead of using the async pipe or toSignal.
To find them systematically rather than by inspection, I would grep for .subscribe( and for assignments to this. inside callbacks, and I would lean on end-to-end tests, since the failure is always visible as "the screen does not change".
The fix in every case is to put the state in a signal. Where that is genuinely impractical mid-migration, inject(ChangeDetectorRef).markForCheck() in the callback is the bridge — and each one is a marker for work not yet done.
Land it The migration is not really about zones; it is about making every piece of template-visible state observable, which is the design you wanted anyway.
- "What order would you do the migration in?"
Three stages, none of which is the switch itself. First convert component state to signals and inputs to
input(), feature by feature, while Zone.js is still there — nothing breaks and the work is valuable on its own.Second, set every component to
OnPush. That surfaces most of the same bugs while the zone is still a safety net, so failures are recoverable and localised.Only then flip the provider, and concentrate testing on screens with third-party widgets, since those are where the remaining non-signal state hides.
- "How do you stop new code reintroducing the problem?"
A lint rule against bare
.subscribe()in components is the highest-value one, since it pushes people totoSignalor theasyncpipe.Beyond that, code review focused on one question — "is every field this template reads a signal?" — plus keeping zoneless on in development so the failure is immediate rather than discovered in production.
Q32. "What was NgZone.runOutsideAngular for, and is it still needed?"
Reveal answer
Strong answer It ran a callback in a context Zone.js did not watch, so the asynchronous work inside it did not trigger change detection.
The canonical uses were high-frequency work: a requestAnimationFrame loop for an animation, a mousemove listener during a drag, a third-party library that polls on a timer. Without it, each tick forced a whole-tree check and the page burned CPU while idle.
The pattern was to run the loop outside and then wrap only the part that genuinely changed state in ngZone.run(...).
In a zoneless application it is unnecessary and meaningless — nothing is patched, so an unwatched timer is simply a timer. The equivalent concern becomes making sure the loop only sets a signal when something a template reads actually changed.
Land it It is the clearest illustration of why zoneless exists: an entire class of performance workaround disappears when the framework stops guessing.
- "How do you do a sixty-frames-per-second animation loop in a zoneless app without re-rendering constantly?"
Keep the per-frame work out of the framework entirely. Start the
requestAnimationFrameloop inafterNextRender, write directly to the element or the canvas, and never set a signal in the loop.Set a signal only at meaningful boundaries — the animation finished, the user dropped the item — so Angular renders a handful of times rather than sixty times a second.
If the animated component also has ordinary bindings,
cdr.detach()with manualdetectChanges()at your own rate is the heavier tool for the same goal.
Q33. "What does ApplicationRef.isStable mean, and why does anyone care?"
Reveal answer
Strong answer Stability means the application has no pending work: no scheduled change detection, no in-flight tasks it knows about.
Three things depend on it. Server-side rendering waits for stability before serialising the HTML, so a never-stable app produces a hanging or timing-out request. Service worker registration is deliberately delayed until stable, so it does not compete with startup. And test harnesses use it to know when to assert.
The classic bug is an interval or a never-completing stream started at bootstrap: under Zone.js the application is never stable, so SSR hangs and the service worker never registers, and both symptoms look unrelated to the timer that caused them.
Land it "SSR times out under load" and "the service worker never installs" are the same root cause more often than not, and it is usually one polling timer.
- "How do you fix a timer that must exist?"
Start it in
afterNextRender, which does not run on the server at all, so the render can finish. On the client it starts after the first paint, which is also better for startup.If it must start earlier, guard it with
isPlatformBrowser, or make the stream complete after a bounded number of emissions so stability is eventually reached.
Q34. "Explain the lifecycle hooks that still matter and what replaced the rest."
Reveal answer
Strong answer Two still earn their place. ngAfterViewInit, for the rare cases needing a real DOM element — measuring, focusing, handing a node to a third-party library — though afterNextRender is the more precise tool because it also excludes the server. And ngOnDestroy, for cleaning up anything Angular did not create.
ngOnChanges is replaced by computed over signal inputs: instead of being told an input changed and comparing previous with current, you declare a derivation that is always correct.
ngOnInit is usually unnecessary now. It existed because inputs are not set when the constructor runs; signal inputs remove that ordering problem, since a computed reading them simply has no value until they do.
The content and view hooks — ngAfterContentInit, ngAfterViewChecked and their siblings — are largely replaced by signal queries, which have a value when they have a value rather than at a specific hook.
Land it The direction is consistent: hooks tell you to go and look, reactivity declares a relationship that stays true, and the second needs no ordering knowledge.
- "What is the exact order of the hooks on first render?"
Constructor, then
ngOnChangesfor the first input values, thenngOnInit, thenngDoCheck, thenngAfterContentInitandngAfterContentChecked, thenngAfterViewInitandngAfterViewChecked.Content hooks come before view hooks because projected content belongs to the parent and is resolved earlier. On later passes,
ngOnChangesruns only when an input changed, and the checked hooks run every pass — which is why putting work inngAfterViewCheckedis a reliable way to make a page slow.- "What replaces
ngOnDestroyoutside a component?" inject(DestroyRef).onDestroy(fn), which works anywhere there is an injection context — services, functions, guards. It is also whattakeUntilDestroyed()uses internally.That matters for a service provided on a route or a component, where there is a real destruction moment and no class hook you would otherwise reach for.
Q35. "How do animations work in Angular now, and what changed?"
Reveal answer
Strong answer Angular's own animations package gave you a domain-specific language — trigger, state, transition, animate — driven from the template and able to animate elements entering and leaving.
Its cost is bundle size and a second mental model, and modern CSS covers most of what people used it for: transitions, keyframes, and now view transitions for cross-page morphs.
So the current guidance is CSS first. Use the router's view transition support for page-level changes, and reach for the animations package only when you need coordinated sequences, animation callbacks, or reliable enter and leave hooks that CSS alone cannot express because the element is removed before it can animate out.
That last case is the honest remaining gap: animating an element out requires something to delay its removal, and that is what the animations package or a small directive gives you.
Land it The question behind the question is usually bundle awareness — knowing that pulling in the animations package for one fade is a poor trade.
- "What is
withViewTransitions()?" A router feature that wraps navigation in the browser's View Transitions API, so the old and new pages cross-fade or morph rather than swapping instantly.
You enable it in
provideRouterand then style the transition in CSS, optionally naming elements withview-transition-nameso a specific item morphs from list to detail.It degrades gracefully: browsers without support simply navigate instantly, so it needs no feature detection.
Q36 · Scenario. "The Angular DevTools profiler shows one component checked 400 times during a single drag. What do you conclude?"
Reveal answer
Strong answer That a mousemove handler is triggering change detection on every event, which is roughly the frame rate times the drag duration.
Under Zone.js that happens automatically because addEventListener is patched. In a zoneless app it means the handler is setting a signal on every move.
Two fixes depending on what the drag is for. If the moving thing is purely visual, keep it out of the framework: update the element's transform directly inside a requestAnimationFrame loop and set a signal only when the drag ends.
If other components genuinely need the live position, throttle the signal updates to animation frames rather than raw events, so at most one render per frame.
I would also check whether the checked component even reads the dragged position — 400 checks of a component that does not care means the marking is too coarse.
Land it The general principle is that pointer-rate events should never be the framework's rate; convert them to frame rate or to meaningful boundaries before they touch state.
- "How would you measure whether the fix worked?"
Re-record the same drag in the profiler and compare the check count and the total scripting time. A fix that takes 400 checks to 30 is visible immediately in that number.
I would also look at Chrome's performance panel for dropped frames during the drag, because the user-visible symptom is stutter, and the check count is only a proxy for it.
Q37. "What is afterNextRender and how does it differ from an effect?"
Reveal answer
Strong answer afterNextRender registers a callback that runs once, in the browser only, after the next render completes. There is also afterEveryRender for the repeating case.
Three differences from an effect matter. It does not run during server-side rendering, so it is the correct home for anything touching document, window or a third-party widget. It is not reactive — it does not track signals and does not re-run when data changes. And it runs strictly after the DOM is written, with phases you can select so reads and writes are batched separately to avoid layout thrashing.
An effect is reactive, runs on both platforms, and is about data. Use an effect to react to state; use afterNextRender to touch the DOM.
Land it Putting document access in an effect is one of the most common ways to break SSR while everything works perfectly on localhost.
- "What are the phases for?"
To separate reads from writes. If several components each measure an element and then set a style, interleaving those forces the browser to recompute layout between every pair — layout thrashing.
The phases let Angular run all the measuring callbacks together and then all the mutating ones, so layout is computed once. It is the same reasoning behind the classic "batch your reads, then your writes" advice, applied framework-wide.
Q38. "How would you explain the difference between Angular's rendering model and React's to someone who only knows React?"
Reveal answer
Strong answer React re-runs a component function to produce a description of the UI, diffs that description against the previous one, and applies the differences. The component body is the unit, and re-rendering means calling it again.
Angular compiles each template into an update function with a fixed set of binding slots. It re-evaluates those expressions and compares each against its stored slot, writing only the differences. There is no intermediate tree and no diff.
The practical consequence is where the granularity lives. In React, re-rendering a component re-runs everything in it, which is why memo, useMemo and useCallback exist — and why the React Compiler now inserts that memoisation for you.
In Angular, a check re-evaluates bindings but does not re-run the class, so component state is not recreated and there is no equivalent of the stale-closure problem.
Land it Both are converging on fine-grained reactivity — Angular through signals, React through its compiler — but from opposite starting points, and the vocabulary reflects that history.
- "So is Angular's model strictly better?"
No, it trades differently. Angular's fixed binding slots make checks cheap and avoid a diff, but the template is a restricted language — no arbitrary JavaScript, and dynamic structure needs specific mechanisms.
React's model is more uniform: the UI is a function of state written in ordinary JavaScript, which is conceptually simpler and composes in ways templates cannot. The cost was the re-render granularity problem, which is what the compiler addresses.
I would not claim either is better in the abstract; I would say Angular's model makes the cost of a render more predictable and React's makes the code more uniform.
Q39. "What is the point of @let, and how is it different from a computed?"
Reveal answer
Strong answer @let declares a read-only local name inside a template, scoped to its block and everything nested in it. It exists so an expression needed twice is written once.
It is not a cache across renders. The expression is evaluated as part of the template's update pass, like any other binding, so it saves repetition and one evaluation within a pass — not work across passes.
A computed is the opposite: it lives in the class, it is cached across renders, and it only re-runs when its dependencies change.
So @let is for readability and for naming an intermediate; anything expensive belongs in a computed.
Land it Use @let to stop repeating user()?.profile?.displayName three times; use computed when the value costs something to produce.
- "What did people do before it existed?"
They abused
*ngIf="expr as name", which binds a name but also conditionally renders — so a value that was legitimately0,''orfalsemade the whole block disappear.That is a genuinely common bug: a count of zero rendering nothing instead of "0 items".
@letremoves the coupling between naming and conditioning, which is why it is a real improvement rather than sugar.
Q40. "A component's template reads a signal from a service. Does that component re-render when any part of the service changes?"
Reveal answer
Strong answer No — only when the specific signals it read change. The dependency is per signal, not per service, and it is recorded from the actual reads during the last render.
So a component reading store.count() is unaffected by store.lines() changing, unless count is a computed derived from lines, in which case it is affected only if the count value actually differs.
That last clause is the useful one: adding a line and removing one in the same update leaves count unchanged, so a component showing only the count is not re-rendered at all.
The failure case is a service that exposes one coarse signal holding a whole object. Then every field change invalidates every consumer, and the precision is lost — not because signals are coarse, but because the state was modelled coarsely.
Land it Signal granularity is a modelling decision: expose derived computeds for what consumers actually read, rather than one blob they all depend on.
- "Does reading a signal in a class method, not the template, create a dependency?"
Only if that method is called from within a reactive context — inside a
computed, aneffect, or a template expression. The tracking is about where the read happens, not about which function contains it.So a method called from a click handler reads the current value and creates no dependency, which is usually what you want. The same method called from a computed does create one, which is how helper functions compose into derivations.
Ten scenario questions that close out the reactivity block. Answer each in diagnosis order — what you look at first, and what that observation rules out.
Q41 · Scenario. "A dashboard with 12 widgets re-renders all of them whenever one widget's data arrives. Diagnose."
Reveal answer
Strong answer Something all twelve depend on is changing, and there are three usual candidates.
A shared coarse signal. If the store exposes one dashboardState object and each widget reads it, any field changing invalidates all twelve. The fix is per-widget computeds, or separate signals per data source.
The parent's template rebuilds the inputs. A binding like [config]="{ theme: theme(), size: size() }" constructs a new object on every check, so every child sees a changed input regardless of whether anything meaningful moved. Hoist it into a computed.
A method call in the parent's template that returns a new array of widget models each check, with the same effect on identity.
I would confirm with the profiler: it shows how many times each widget was checked and how long each took, which distinguishes "all twelve are marked" from "one is slow".
Land it Object literals in templates are the quiet version of this bug — they look like configuration and behave like a fresh identity on every render.
- "How do you avoid the object-literal-in-template problem generally?"
Pass primitives where you can —
[theme]="theme()" [size]="size()"— since primitives compare by value and never produce a false change.Where a grouped object genuinely helps the API, build it in a
computedso its identity is stable until an input actually changes. The rule I apply in review is that no binding should contain{or[as a literal.
Q42 · Scenario. "A modal opens instantly but closes with a 300 ms delay on a slow laptop. Where do you look?"
Reveal answer
Strong answer Asymmetry between open and close is the clue: opening adds a component, closing removes one, and removal is the expensive direction when there is teardown work.
Candidates in order. Destroying many child components, each running cleanup — a modal containing a large table destroys every row. Subscriptions and effects being torn down, cheap individually and not in the hundreds. A third-party widget's destroy() doing real work. And an animation with a duration that simply has to elapse.
I would record the close in Chrome's performance panel first, because it answers whether the time is scripting, layout or simply waiting — and if it is waiting, no amount of Angular tuning will help.
If it is teardown of many children, the fix is usually to not render them all in the first place: virtual scrolling or pagination inside the modal reduces both open and close cost.
Land it Measure before optimising, and specifically distinguish waiting from working — a CSS transition duration and a 300 ms teardown look identical to the user and have opposite fixes.
Q43 · Scenario. "Two tabs of the same app show different data after a save in one of them. Is that a bug?"
Reveal answer
Strong answer It is expected behaviour, and whether it is a defect depends on the product. Each tab is a separate JavaScript context with its own services, signals and caches; nothing is shared unless you share it deliberately.
If the product needs consistency, there are three mechanisms in increasing order of cost. The storage event fires in other tabs when localStorage changes, which is enough to say "something changed, refetch". BroadcastChannel is the purpose-built API for messaging between tabs of the same origin. And a server push — WebSocket or server-sent events — handles the general case where another user made the change, not just another tab.
There is also a cheap partial answer: refetch on window focus, which covers the common "I switched tabs and expected fresh data" case with a few lines.
Land it The framing that matters is that your client state is a cache of server state, so this is a cache-invalidation question rather than an Angular question.
- "Which would you choose for a shared shopping cart?"
The server, because the cart must also survive a device change and a browser restart, and because two tabs are not the hard case — two devices are.
So the cart lives server-side, the client holds a cache, and tab synchronisation falls out of refetching on focus plus a push when the server changes it. Using
BroadcastChannelalone would keep two tabs consistent with each other and both wrong relative to the phone.
Q44 · Scenario. "After a deploy, users on the old bundle get errors when they navigate to a lazy route. Why, and what do you do?"
Reveal answer
Strong answer Their loaded application references chunk filenames with the old content hashes. The deploy replaced them with new filenames, so the request for the old chunk returns 404 and the dynamic import rejects.
The user sees a navigation that silently does nothing, or an unhandled rejection, depending on whether anything catches it.
Three fixes, and a good answer names more than one. Keep old chunks available for a grace period rather than deleting them on deploy — the cheapest and most effective. Detect the failed chunk load and reload the page once, which recovers the user at the cost of losing unsaved state. And notify users that a new version is available so they choose when to reload; Angular's service worker package has this built in with SwUpdate.
I would do the first always, and add the third for applications where people keep a tab open for hours.
Land it Deleting old chunks on deploy is the actual defect; the client-side recovery is a mitigation for the window you cannot avoid.
- "How would you implement the reload-once fix safely?"
Catch the rejection from the dynamic import — the router surfaces it as a navigation error — and check a session flag before reloading, so a genuinely broken chunk cannot cause an infinite reload loop.
I would also avoid reloading if the user has unsaved work, and prefer prompting instead. A silent reload that discards a half-written form is worse than the error it replaced.
Q45. "What is the difference between structural and attribute directives at the compiler level?"
Reveal answer
Strong answer An attribute directive attaches to an existing element and can read and write its properties, add listeners and inject things from its injector. It never controls whether the element exists.
A structural directive controls instantiation. The asterisk syntax is sugar: *ngIf="x" expands to wrapping the element in an <ng-template> with the directive applied to it.
The directive receives a TemplateRef, which is the un-rendered blueprint, and a ViewContainerRef, which is a place to put views. It calls createEmbeddedView to render and clear to remove.
That is why a structural directive can render its template zero, one or many times, and why the old else-branch needed a separate named template — there was no syntax for a second blueprint.
Land it The built-in control flow replaced the three common structural directives with real syntax, but the extension mechanism is unchanged and is still how you write a *hasPermission.
- "Why could you never put two structural directives on one element?"
Because each one wants to wrap the element in its own template, and the expansion is ambiguous — there is no defined order and no way to express which wraps which.
The workaround was an
ng-containerto host one of them. The built-in control flow removes the problem entirely, since@ifand@forare blocks that nest explicitly and the nesting order is visible in the source.
Q46. "How does Angular decide whether to reuse a component instance during navigation?"
Reveal answer
Strong answer By default the router reuses a component when the matched route configuration is the same and only the parameters differ. Navigating from /tasks/42 to /tasks/99 reuses the instance and updates the inputs.
That default is why ActivatedRoute.snapshot.params read once in a constructor is the classic stale-page bug — the constructor never runs again.
With withComponentInputBinding() the parameter arrives as a signal input, so a reused component simply sees a new value and anything derived from it recomputes. That is the modern answer and it needs no lifecycle awareness.
If you genuinely want a fresh instance per parameter, runGuardsAndResolvers: 'paramsChange' plus a custom RouteReuseStrategy can force it — but wanting that is usually a sign that some state should have been derived rather than initialised.
Land it Reuse is a performance feature and a correctness trap, and signal inputs convert it from something you must remember into something that just works.
- "What is
RouteReuseStrategyactually for?" Controlling whether a detached route subtree is stored and restored — the "keep the search results and scroll position when I go back" behaviour.
You implement it to cache a component tree on leaving a route and reattach it on return, which preserves scroll, form state and loaded data without refetching.
It is powerful and easy to get wrong: cached trees keep their subscriptions alive, so a careless implementation is a memory leak with extra steps. I would reach for it only when the product genuinely needs restore-on-back and simpler options — URL state plus a cached resource — are not enough.
Q47. "What happens if a signal is set during a change detection pass?"
Reveal answer
Strong answer It depends on where in the pass, and this is exactly the territory of the ExpressionChanged error.
If the write happens before the affected view is checked, the pass simply picks up the new value and everything is consistent.
If it happens after that view was already checked — from a child's lifecycle hook, or from an effect that runs mid-cycle — then the rendered DOM no longer matches the state. In development the verification pass catches it and throws; in production it does not throw and the screen can show a value that is one render behind.
Angular also guards against a specific pathology: a write that keeps re-dirtying views can loop, and the framework will eventually throw rather than spin forever.
Land it The reliable way to stay out of this is to make derived values computed, because a value nobody writes cannot be written at the wrong time.
- "Is setting a signal inside a template expression allowed?"
Templates cannot contain assignments outside event bindings, so you cannot write
x.set(1)in an interpolation. But you can call a method that does it, and that is a genuine hazard — the method runs on every check and writes on every check.The result is either an ExpressionChanged error or an infinite render loop. It is the strongest argument for the rule that template expressions must be side-effect free.
Q48. "How would you build a component that must react to an element's size?"
Reveal answer
Strong answer With a ResizeObserver, connected to a signal, set up in afterNextRender so it never runs on the server.
I would get the element with viewChild, create the observer in afterNextRender, and have its callback set a signal holding the dimensions. Everything downstream — a computed deciding between a compact and a full layout, a chart's dimensions — then derives from that signal.
Cleanup is inject(DestroyRef).onDestroy(() => observer.disconnect()), and it matters, because an undisconnected observer holds the element and therefore the component.
I would also throttle: resize callbacks fire at high frequency during a drag of the window edge, and setting a signal on each one is the same problem as the mousemove question. Coalescing to animation frames is usually enough.
Before any of that I would ask whether CSS container queries solve it, because if the requirement is "lay out differently when narrow", that is now a pure CSS feature with no JavaScript, no observer and no leak.
Land it Reaching for the platform first is the senior instinct — container queries handle the layout case entirely, and the observer is for when a value must reach JavaScript.
Q49. "What is the cost of a component, concretely? When does 'too many components' become the problem?"
Reveal answer
Strong answer Each component instance costs an LView array, one slot per binding, its own injector node if it has providers, and its DOM nodes. Creation costs the create branch of the template function; each check costs one evaluation and comparison per binding.
So the unit that matters is bindings, not components. A hundred components with three bindings each is cheaper to check than ten with a hundred.
It becomes the problem in the thousands of DOM nodes, and the symptom is usually memory and creation time rather than check time — a table of 500 rows with 20 elements each is 10,000 nodes, and the browser's own layout cost dominates anything Angular does.
The fixes in order are: render less — pagination or virtual scrolling; simplify each row so a row is a handful of elements rather than a nested component tree; and only then look at change detection.
Land it When a list is slow, the browser's layout and paint is usually a bigger share than Angular's checks, and the performance panel tells you which in about thirty seconds.
- "Is splitting a big component into small ones good or bad for performance?"
Usually good, because it creates skip boundaries. With
OnPush, a small child whose inputs did not change is skipped entirely, whereas one large component is all-or-nothing — any change re-evaluates every binding in it.The cost is a slightly larger memory footprint per instance and marginally more creation work. That trade is nearly always worth it, and it is also better for readability, which matters more.
Q50 · Design. "Design the rendering strategy for a live trading screen: 200 rows, each updating several times per second."
Reveal answer
The real test Whether you reduce the update rate before optimising the framework.
Strong answer The first decision is to decouple the data rate from the render rate. A feed at several updates per second per row across 200 rows is over a thousand updates a second, and no rendering strategy makes that sensible — the screen refreshes 60 times a second and the user reads perhaps twice.
So I would buffer incoming messages and flush at most once per animation frame, applying the latest value per instrument. That alone takes a thousand updates a second down to sixty at worst.
Second, keep identity stable and per-row. One signal per row, or a row list where only changed rows get new object identities, so a price change on one instrument marks one row dirty and not the table.
Third, virtualise. Only about 30 rows are visible; the other 170 should not exist in the DOM. That also bounds the flush cost regardless of feed size.
Fourth, keep the row template small — a handful of elements, formatting done in computed or a pure pipe, no nested component tree per cell.
For the extreme case — a full order book — I would take the flashing cells out of the framework entirely: a canvas or direct DOM writes inside a requestAnimationFrame loop, with Angular owning the surrounding chrome. That is a deliberate exception and I would document why.
Land it The order matters: coalesce the feed, then bound the DOM, then make identity precise — and only leave the framework when a profile proves the remaining cost is Angular's rather than the browser's.
- "How would you show a price flash on change without re-rendering everything?"
With CSS. Toggle a class for a few hundred milliseconds and let a keyframe animation do the flash, rather than driving the animation from state.
The class toggle is one binding on one row. Driving it from a timer per row would be 200 timers and 200 signal writes, which is the problem again in a different shape.
- "What would you measure to know it is fast enough?"
Dropped frames during a live feed at production rates, from Chrome's performance panel, on the hardware traders actually use — which for a desk is often a locked-down machine slower than a developer laptop.
I would also measure Interaction to Next Paint for the actions people take under pressure, such as clicking a row to open a ticket. A screen that renders smoothly but responds to a click in 300 ms is the failure that matters here.
10 · DrillDependency Injection, RxJS & Async — Q51–Q100
This block covers the second and third of the three questions: who owns this instance, and what is still subscribed.
These are where the expensive production bugs live. A service that exists twice produces a screen that half-updates; a subscription that never ends produces a tab that dies after six hours; the wrong flattening operator produces a race condition that reproduces once a week and never in development.
Answer each one in the order you would actually investigate.
Ten questions on where instances come from, how many there are, and when they die.
Q51. "Describe Angular's injector hierarchy precisely — all of it."
Reveal answer
The real test Whether you know there are two trees, not one.
Strong answer There are two parallel hierarchies and they are searched in a fixed order.
The ElementInjector tree follows the component structure. Every component and directive has a node, and its parent is the component that rendered it. Providers in a @Component({ providers: [...] }) array live here.
The EnvironmentInjector tree follows configuration. The root one holds everything from app.config.ts and every providedIn: 'root' service; a lazy route with its own providers creates a child.
Resolution walks the element chain first, all the way up. Only when that is exhausted does it move to the environment chain for that part of the tree and walk up to the root. Failing both, it reaches the NullInjector, whose only job is to throw NG0201.
That order is why a component-level provider always shadows a root one, however far apart they are.
Land it Most "why do I have two instances" and "why is this null" questions are answered by stating the search order out loud and asking which tree the provider is in.
- "Where does a lazy route's injector sit?"
It is a child environment injector, created when the route activates and destroyed when you navigate out of that subtree. Its parent is the root environment injector, or the nearest ancestor route's if routes are nested.
So a service provided on a lazy route is a singleton for that feature and gets a fresh instance each time the user enters it. That is often exactly right — feature state that should reset — and occasionally a surprise if you cached something in it.
- "What is
providedIn: 'platform'?" An injector above the application root, shared across every Angular application bootstrapped on the same page. It exists for micro-frontend hosts and for the rare case of multiple applications sharing one service.
Outside those, it is almost always wrong: it survives application teardown, so anything it holds outlives what you expect.
Q52. "Explain self, skipSelf, optional and host with a real use for each."
Reveal answer
Strong answer { self: true } looks only in this injector and does not walk up. I use it for a directive that must be applied alongside a specific provider on the same element, so a missing one fails loudly at development time instead of silently picking up a distant instance.
{ skipSelf: true } starts the search at the parent. It enables the recursive pattern: a component that provides itself and asks for its own type from the parent, which is how nested trees compute their depth and how nested form directives find their container.
{ optional: true } returns null instead of throwing. Right for genuinely optional collaborators and required for the outermost node of any recursive pattern, which has no parent.
{ host: true } stops the element search at the host component boundary. It keeps a directive from reaching past the component it was applied inside, which matters for library directives that should not depend on the wider application.
Land it The recursive pattern needs skipSelf and optional together — without the first it finds itself and recurses forever, without the second the root throws.
- "Write the depth-tracking component."
@Component({ selector: 'app-panel', providers: [Panel] }), then in the classprivate parent = inject(Panel, { skipSelf: true, optional: true })andreadonly depth = computed(() => (this.parent?.depth() ?? -1) + 1).Each panel provides itself so its children can find it; each asks its parent, skipping its own injector; the outermost gets
nulland starts the count. Depending on file layout you may needforwardRef, because the class is referenced inside its own decorator.
Q53. "What is the injection context, and why does inject() throw outside it?"
Reveal answer
Strong answer inject() has no argument saying which injector to use. It reads an ambient variable that Angular sets while it is constructing something, meaning "resolve against this injector".
Outside those windows the variable is unset, so inject() cannot know who is asking and throws NG0203.
The windows are: field initialisers and constructor bodies of components, directives, pipes and services; provider factory functions; route guards, resolvers and functional interceptors, because the router and HTTP client establish a context before calling them; and inside runInInjectionContext(injector, fn).
Not included: click handlers, setTimeout callbacks, promise continuations, and anything that runs after construction has finished.
Land it Needing runInInjectionContext in application code is a smell — inject the dependency as a field like everything else; it earns its keep in libraries.
- "When is
runInInjectionContextgenuinely necessary?" When you must create something that needs a context outside construction — an
effect, a resource, or atakeUntilDestroyedin a method rather than a field.Also in libraries that accept a user-supplied factory and must run it with the caller's injector, and in dynamically created components where you build the injector yourself.
The pattern is to capture
private injector = inject(Injector)as a field and use it later, which is legitimate precisely because the capture happened in a valid context.
Q54 · Scenario. "A cart badge in the header never updates, though the cart page works. Diagnose."
Reveal answer
Strong answer First hypothesis: there are two CartService instances, and the header has a different one from the cart page.
I would test it in one line — inject the service in both places and log a === b, or set a unique id on construction and log it. If they differ, stop looking at the badge entirely.
The usual cause is a providers: [CartService] array on a component or a lazy route, which creates a scoped instance that shadows the root one for everything inside it.
If the instances are the same, the second hypothesis is that the badge reads a plain field rather than a signal, so nothing marks the header when the cart changes. In a zoneless application that is silent.
Third, and less likely, the header component is an OnPush component whose parent is never marked, so the pass does not reach it.
Land it The identity check first, always — it takes thirty seconds and it either eliminates or confirms the most common cause outright.
- "How do you prevent this class of bug?"
By treating a
providersarray on a component as a deliberate statement that this state is per instance, and reviewing every one of them with that question.A lint rule can flag component-level providers for services whose names suggest application scope, though the reliable control is a convention: shared stores are
providedIn: 'root'and nothing else provides them.- "Could a lazy route cause it even without an explicit provider?"
Yes, if the service is provided in the route's
providersarray — which people add when they want feature-scoped state and forget affects everything under that route.It can also happen with an old
NgModulethat lists the service in its own providers and is imported by a lazy module: the lazy module gets its own instance while the eagerly loaded header has the root one. That combination is the classic version of this bug in pre-standalone codebases.
Q55. "What are multi-providers and what are they used for?"
Reveal answer
Strong answer A provider declared with multi: true contributes to an array instead of replacing the previous registration for that token. Injecting the token returns every registration.
It is the extension-point mechanism. HTTP interceptors were built on it before the functional form, APP_INITIALIZER uses it so several parts of an app can register startup work, and validators use it so multiple sources can attach rules to the same control.
You reach for it when the answer to "who may register one of these" is "anyone, including code I have not written".
The trap is mixing forms: a non-multi provider for a token that others registered as multi throws, because Angular cannot decide whether the token yields a value or an array.
Land it If you are designing a library and want consumers to plug in behaviour without editing your code, this is the mechanism rather than a registry service.
Q56. "You have a circular dependency between two services. What do you do?"
Reveal answer
Strong answer First I would distinguish the two things people call a cycle, because they have different fixes.
A declaration-order problem is when a class is referenced before its declaration has been evaluated — common with a class referring to itself in its own decorator, or two classes in one file. forwardRef(() => B) solves that by deferring the reference to call time.
A genuine cycle — A needs B to do its job and B needs A — is a design problem that forwardRef only makes lazier, not correct. Construction still cannot complete cleanly.
My fixes for a genuine cycle, in order of preference: extract the shared responsibility into a third service that both depend on; invert one direction so the dependency becomes a method parameter or an event rather than an injection; or, as a last resort, have one side inject Injector and resolve the other lazily at call time.
Land it A cycle in the injector graph is usually a cycle in the domain model, and fixing the domain is cheaper than working around the injector.
Q57. "How would you provide different implementations of a service for different environments?"
Reveal answer
Strong answer With an abstract class or an InjectionToken as the contract, and a useClass or useFactory provider choosing the implementation in app.config.ts.
I prefer an abstract class over an interface, because an interface is erased at compile time and cannot be a token, whereas an abstract class is a real runtime object that also gives you the type.
The choice itself I would make from injected configuration rather than from a build-time environment file where possible, so the same bundle can run in several environments — which matters for a build-once, deploy-many pipeline.
In tests the same seam gives you substitution with one provider line, which is the main practical payoff.
Land it Deciding implementations from injected configuration rather than compile-time flags is what lets one artefact be promoted through environments instead of rebuilt per environment.
- "What is wrong with importing from
environment.tsdirectly?" It bakes the decision into the bundle at build time, so staging and production are different artefacts and you cannot promote the exact bytes you tested.
It is also invisible to dependency injection, so it cannot be overridden in a test without module mocking, and it encourages sprinkling
if (environment.production)through code that should not know.Fetching configuration at startup — or serving it from the same host — keeps one bundle and makes the values injectable and overridable.
Q58. "What does APP_INITIALIZER do and when would you use it?"
Reveal answer
Strong answer It registers a function that runs before the application bootstraps, and if it returns a promise, bootstrap waits for it. It is a multi-provider, so several parts of the app can register work.
The legitimate use is configuration that everything depends on: fetching runtime settings, loading feature flags, restoring an authentication session, or initialising an internationalisation bundle.
The cost is that it delays first paint by exactly its duration, so it should do one small thing. A slow initialiser is a blank screen with no spinner, because nothing is rendered yet.
An initialiser that fails needs a decision: either bootstrap anyway in a degraded mode, or show a static error page from index.html. Letting the promise reject silently gives the user a permanently blank page.
Land it Anything that can be loaded lazily should be, because everything in an initialiser is time the user spends looking at nothing.
Q59. "How do you dynamically create a component at runtime, and when is that the right tool?"
Reveal answer
Strong answer With ViewContainerRef.createComponent(ComponentClass), which returns a ComponentRef you can set inputs on with setInput() and destroy explicitly.
You can pass an environmentInjector and an injector so the created component resolves dependencies against a scope you choose, and projectableNodes to supply projected content.
It is the right tool when the set of components is not known at compile time: a dashboard where users choose widgets, a form built from a server-supplied schema, a notification system rendering arbitrary content.
It is the wrong tool when the choice is a fixed small set, where @switch in a template is clearer, keeps the type checking, and needs no manual destruction.
The responsibility that comes with it is lifecycle: you destroyed nothing automatically, so the ComponentRef must be destroyed, usually in DestroyRef.onDestroy.
Land it Dynamic creation trades compile-time safety for flexibility, so it should be confined to a small factory rather than spread through feature code.
- "How does the CDK overlay use this?"
It creates a detached DOM host positioned relative to an origin element, then attaches either a
ComponentPortalor aTemplatePortalinto it — the same dynamic-creation machinery with positioning, scroll strategies, backdrop and focus management on top.That is why building dialogs and menus on the CDK is worth it: the creation part is easy and the long tail of focus restoration, escape handling and repositioning is not.
Q60. "What does 'tree-shakeable provider' mean and why does providedIn enable it?"
Reveal answer
Strong answer Tree-shaking is a bundler removing code it can prove is unreachable. For a service, that means proving nobody injects it.
With providedIn: 'root' the registration lives on the class itself, in its own decorator metadata. If no code references the class, the whole thing — class and registration — is unreachable and can be dropped.
With the older pattern, the service was listed in an NgModule's providers array. That array is reachable code referencing the class, so the bundler must keep it even if nothing injects it. Every unused service shipped.
The same reasoning explains the provide* functions replacing forRoot(): you only reference the features you switch on, so the rest tree-shakes.
Land it It is a small idea with a real effect on large codebases — a hundred services nobody imports any more used to be a hundred services in the bundle.
The block that most reliably separates candidates. Every question here is really "what happens to the second value while the first is in flight".
Q61. "Compare switchMap, mergeMap, concatMap and exhaustMap, and give the canonical use of each."
Reveal answer
The real test Whether you frame it as a concurrency decision rather than four names.
Strong answer All four map each source value to an inner observable and flatten the results. They differ only in what happens when a new value arrives while a previous inner observable is still running.
switchMapcancels the previous and switches. Use when only the latest result matters — type-ahead search, loading a detail view from a route parameter.mergeMapruns both concurrently, results in completion order. Use when every request must happen and order does not matter — analytics events, parallel uploads.concatMapqueues the new one until the previous completes. Use when every request must happen, in order — sequential writes to one record, an ordered command queue.exhaustMapignores new values until the current completes. Use when extra triggers are accidents — a double-clicked submit button, a login form.
My defaults are switchMap for reads and exhaustMap for writes triggered by a button.
Land it Using mergeMap for a search is the classic race condition; using switchMap for a save is the classic data-loss bug — both are the right operator applied to the wrong direction.
- "Why is
switchMapdangerous for writes?" Because cancelling a POST does not undo it. The browser abandons the response, but the server may already have committed the write — so the client thinks nothing happened while the record changed.
Two rapid saves with
switchMapcan therefore produce a first write that succeeded invisibly and a second that overwrote it, or a first that half-completed.exhaustMaporconcatMapkeeps the client's model of what happened accurate.- "How do you limit concurrency with
mergeMap?" Its second argument is a concurrency limit:
mergeMap(fn, 4)runs at most four inner observables at a time and queues the rest.That is the right tool for bulk uploads, where unlimited parallelism will exhaust the browser's connection pool and make everything slower, and where fully sequential is needlessly slow.
Q62. "Where do you put catchError, and why does it matter?"
Reveal answer
Strong answer Inside the inner observable of a flattening operator if you want the outer stream to survive; outside it if you are deliberately ending the stream.
The reason is the observable contract: an error is terminal. Once it propagates to the outer stream, that stream is finished and never emits again — so a search box whose pipeline let one HTTP error escape stops responding permanently, and reloading the page is the only cure.
Placed inside — switchMap(q => this.api.search(q).pipe(catchError(() => of([])))) — the failure is contained to that one request. The outer stream never sees an error and keeps handling keystrokes.
Placed outside the switchMap, catchError does catch it, but its replacement observable becomes the whole stream, so the source is still unsubscribed.
Land it "The search box stopped working and only a refresh fixes it" is almost always a catchError in the wrong place.
- "What is the difference between
retryandrepeat?" retryresubscribes after an error;repeatresubscribes after a completion. Soretry(3)makes up to three more attempts on failure, whilerepeatis for polling a stream that completes each time.Bare
retry(3)is usually too aggressive: three immediate retries against an overloaded server make it worse.retry({ count: 3, delay: (err, n) => timer(1000 * 2 ** n) })gives exponential backoff, and I would also not retry 4xx responses, since a 400 will fail identically every time.
Q63. "What is the difference between a cold and a hot observable, and where does it bite in Angular?"
Reveal answer
Strong answer A cold observable creates its producer per subscription, so each subscriber gets its own execution. http.get() is cold: two subscribers, two requests.
A hot observable has one producer shared by all subscribers. A Subject is hot; a cold observable becomes hot when wrapped in a multicasting operator.
Where it bites is the async pipe used twice on the same observable in one template — two subscriptions, two HTTP requests, and often two spinners that resolve at different times.
The fixes are shareReplay(1), binding once with @if (data$ | async; as data) and reusing the local name, or — best in modern code — toSignal, which subscribes once and shares by construction.
Land it Duplicate network requests visible in the network tab with no obvious second call site is nearly always this.
- "What is the trap in
shareReplay?" By default it never unsubscribes from the source. When the last downstream subscriber leaves, it keeps the source subscription and the replayed value alive forever.
For an HTTP call that completes, harmless. For an
interval, a WebSocket or a router-event stream, it is a permanent leak — the source keeps producing into a buffer nobody reads.shareReplay({ bufferSize: 1, refCount: true })drops the source when the count reaches zero. The default is the historical behaviour and the one people get bitten by.
Q64 · Scenario. "A nested subscribe inside another subscribe appears in review. What do you say?"
Reveal answer
Strong answer That it works and breaks three things, and I would name them rather than calling it a style issue.
Cleanup. The inner subscription is not tied to the outer one, so takeUntilDestroyed on the outer does not end it. Every outer emission creates another inner subscription that nothing closes.
Errors. An error in the inner stream does not reach the outer error handler, so it becomes an unhandled rejection or is swallowed.
Cancellation. If the outer emits again, the previous inner call keeps running and can land after the newer one — a race with no operator to arbitrate it.
The fix is a flattening operator, and which one is the design question: switchMap if only the latest matters, concatMap if every one must happen in order.
Land it One subscription, one cleanup path, one error path — that is what flattening buys, and it is why the nested form is the most common real RxJS defect.
Q65. "How do you combine two streams? Compare combineLatest, forkJoin, zip and withLatestFrom."
Reveal answer
Strong answer combineLatest emits whenever any source emits, giving the latest value of each — but only after every source has emitted at least once. That last clause is the trap: one silent source means no output at all.
forkJoin waits for every source to complete and emits their final values once. It is the promise-all equivalent, right for several HTTP calls in parallel — and it emits nothing if any source never completes or if any errors.
zip pairs values by index: the first of each, then the second of each. It is rarely what you want in an application, and it quietly buffers when sources emit at different rates.
withLatestFrom is asymmetric: it emits only when the primary source emits, attaching the latest from the others. That is the right shape for "on save, also include the current filters".
Land it The asymmetry question decides it: if only one stream should trigger the work, use withLatestFrom, because combineLatest will fire on all of them.
- "Give the classic
combineLatestbug." Combining a route parameter stream with a filter subject that has no initial value. The route emits, the filter never has, so
combineLatestemits nothing and the page stays on its loading state forever with no error anywhere.The fix is
startWithon the source that may not emit, or aBehaviorSubjectwhich always has a current value. With signals the problem does not arise, because a signal always has a value.- "What does
forkJoindo if one request fails?" The whole thing errors and you get no values at all, including from the requests that succeeded. That is often wrong for a dashboard, where three of four panels loading is better than none.
The fix is to
catchErrorinside each inner observable and map failure to a sentinel, soforkJoinalways completes and each panel can decide how to render its own failure.
Q66. "How would you implement a typed, cancellable, retrying data service with RxJS?"
Reveal answer
Strong answer I would compose four concerns and keep each visible.
Typing comes from http.get<T>(), with validation at the boundary if the API is not mine, because the generic is a claim and not a check.
Cancellation comes from the caller's switchMap rather than from the service — the service should return a cold observable and let the consumer decide the concurrency policy.
Retry is retry({ count: 3, delay: (err, n) => err.status >= 500 ? timer(500 * 2 ** n) : throwError(() => err) }), so only server errors and network failures are retried, with backoff, and a 400 fails immediately.
Timeout is timeout(8000), because a request that hangs forever is worse than one that fails — the user sees a spinner with no end.
What I would not do is bake shareReplay or a subscription into the service, because that removes the caller's ability to control lifetime.
Land it A service should return a recipe, not a running thing — the consumer owns concurrency and lifetime, which is what keeps the service reusable.
Q67. "What are the streams that never complete, and what is the cost of forgetting one?"
Reveal answer
Strong answer Router events, fromEvent listeners, interval and periodic timer, form valueChanges and statusChanges, WebSocket and server-sent-event streams, and any Subject you own.
The cost is that the subscription holds a closure over the component, so the component and everything it references cannot be garbage collected. In a single-page application people keep open all day, that accumulates.
Worse than the memory is the behaviour: the callback keeps running on a destroyed component. It writes to signals nobody reads, fires analytics for a page the user left, and can throw because it references things that were torn down.
HTTP calls are the exception — they complete after one value and release themselves, so they need no manual cleanup.
Land it The tell is a handler logging after navigation; the confirmation is a heap snapshot showing the component's instance count climbing.
Q68 · Scenario. "Ten parallel requests all get a 401 and each triggers a token refresh. Fix it."
Reveal answer
Strong answer This is the refresh stampede, and the fix is a single shared in-flight refresh.
In the interceptor, on a 401, I check whether a refresh is already running. If it is, I subscribe to that same observable rather than starting another. If it is not, I start one and store it so the other nine find it.
Concretely: a refresh$ field holding the refresh observable piped through shareReplay(1), cleared when it settles. Each 401 does switchMap from that shared refresh into a retry of its original request with the new token.
Two guards matter. If the refresh call itself returns 401, log out rather than retrying, or a bad refresh token produces an infinite loop. And do not intercept the refresh endpoint itself, for the same reason.
Without this, ten refreshes race, nine of the resulting tokens are invalidated by rotation, and the user is logged out at random.
Land it The shared in-flight observable is the whole pattern — it is the same idea as request coalescing on a server, applied in the browser.
- "How would you test it?"
With
HttpTestingController: fire ten requests, flush all ten with 401s, then assert thatexpectOne('/auth/refresh')matches — exactly one refresh went out. Flush that with a new token and assert the ten originals were retried with the new header.That is a genuinely valuable test, because the bug only appears under concurrency and is nearly impossible to reproduce by hand.
Q69. "When would you still choose RxJS over signals in new code?"
Reveal answer
Strong answer Whenever the problem is about time, sequence or coordination rather than about a current value.
Time: debouncing, throttling, retry with backoff, timeouts, polling. Signals have no temporal operators; Angular 22's debounced() covers one case and nothing beyond it.
Sequences: anything where "it happened twice with the same payload" is meaningful. A signal collapses that into one unchanged value.
Coordination: combining several asynchronous sources, cancelling one when another fires, limiting concurrency across a queue of work.
Long-lived push sources: WebSockets and server-sent events, where the stream abstraction with its completion and error semantics fits naturally.
Everything else — component state, derived values, and straightforward data fetching — I would write with signals and resources.
Land it The dividing line is whether the answer to "what is it now" is sufficient; if you also need "and in what order, and how fast", that is RxJS.
Q70. "What are toSignal's options and what goes wrong without them?"
Reveal answer
Strong answer Three matter.
initialValue gives the signal a value before the source emits. Without it the type is T | undefined, so every template read needs a guard and every computed has to handle undefined.
requireSync: true asserts that the source emits synchronously on subscribe, which makes the type plain T. It is correct for a BehaviorSubject or a startWith pipeline, and throws at construction if the source does not — which is a good failure, because it happens immediately rather than as an undefined three components away.
manualCleanup: true opts out of destroying the subscription with the injection context. It is for genuinely application-lifetime streams and it is the option most likely to be a leak.
By default an error from the source is re-thrown when the signal is read, so an unhandled HTTP error surfaces during rendering rather than being swallowed.
Land it Using requireSync on an HTTP observable is the common mistake — it throws immediately, which is exactly the right behaviour and still surprises people.
Where the application meets an unreliable network. These questions are graded on whether you handle failure as a first-class case rather than an afterthought.
Q71. "How do functional interceptors work, and what belongs in one?"
Reveal answer
Strong answer An interceptor is a function of (req, next) registered with provideHttpClient(withInterceptors([...])). It can transform the request, call next() to continue the chain, and transform or handle the resulting stream.
They run in array order outward and in reverse on the way back, exactly like server-side middleware — so the first listed is outermost and sees the request first and the response last.
What belongs in one is anything every call must do: attaching an authentication header, adding a correlation or trace id, logging slow requests, driving a global loading indicator, retrying idempotent requests, and translating error responses into a consistent shape.
What does not belong is business logic. An interceptor that knows about orders is a coupling that will surprise the next person, because it acts on requests it was never meant to see.
Land it Requests are immutable and you must req.clone() — that is deliberate, so a retry re-sends what was originally issued rather than something an interceptor edited mid-flight.
- "How does an interceptor skip certain requests?"
With
HttpContext, which carries per-request metadata that interceptors can read. You define a token —const SKIP_AUTH = new HttpContextToken(() => false)— and the caller passes{ context: new HttpContext().set(SKIP_AUTH, true) }.That is much better than matching on the URL, which breaks the moment an endpoint moves and couples the interceptor to routing details it should not know.
- "Can an interceptor use
inject()?" Yes — the HTTP client establishes an injection context before calling it, which is one of the main advantages of the functional form over the old class-based one.
The caveat is that
inject()must be called in the interceptor's own body, not inside a later callback such as acatchErrorhandler that runs asynchronously. Capture what you need at the top.
Q72. "Design the error-handling strategy for an application's HTTP layer."
Reveal answer
Strong answer I would split errors into three groups, because they need different handling and mixing them is what produces both silent failures and alert fatigue.
Expected domain errors — a 404 for a record that was deleted, a 409 conflict, a 422 validation failure. These belong to the feature and should be handled where the call is made, producing a message the user can act on. An interceptor must not swallow them.
Cross-cutting authentication and authorisation — 401 and 403. These belong in an interceptor: refresh the token once and retry, or redirect to login, or show a "you do not have access" page.
Unexpected failures — 500s, network errors, timeouts. Retry the idempotent ones with backoff, then surface a generic message with a retry action and report to monitoring with the correlation id.
Two rules across all three: never show a raw exception or status code to a user, and never leave a failed request rendering as an empty state, because "you have no orders" and "we could not reach the server" mean completely different things to the person reading it.
Land it The empty-state-versus-error distinction is the one that generates support tickets, and it is entirely a template decision that costs one extra branch.
- "What does a global
ErrorHandleradd?" It catches everything that escaped — errors thrown in lifecycle hooks, in template expressions, in effects, and unhandled rejections. Replacing it lets you report to monitoring with user and route context rather than losing them to the console.
It is a backstop, not a strategy: an application that relies on it for HTTP failures will show the user nothing useful, because by then the context of which action failed is gone.
Q73. "What is the difference between HttpClient's XHR and fetch backends?"
Reveal answer
Strong answer As of Angular 22 the fetch backend is the default and withFetch() is no longer needed.
Fetch is the modern platform API, works in service workers and on the server without a polyfill, supports streaming responses, and integrates with abort signals for cancellation.
The one capability XHR retains is upload progress events. Fetch cannot report how much of a request body has been sent, so uploads with a progress bar still require the XHR backend, selected with withXhr().
Angular 22 also split the old reportProgress option into reportDownloadProgress and reportUploadProgress, making that constraint explicit at the call site rather than a runtime surprise.
Land it Download progress works on both; upload progress is the reason a codebase still has an XHR backend configured somewhere.
Q74 · Scenario. "A dashboard fires 14 requests on load and takes 4 seconds. What do you do?"
Reveal answer
Strong answer First measure, because "14 requests" and "4 seconds" have several possible relationships.
In the network tab I would check whether they ran in parallel or in a waterfall. A waterfall means something is sequential — dependent requests, or a concatMap where mergeMap was meant — and fixing the sequencing is the whole win.
If they are parallel, I would check whether the browser's per-host connection limit is queuing them, and whether the server is the bottleneck by looking at time-to-first-byte per request.
Then the structural fixes, in order of value. Do not fetch what is not visible: panels below the fold go behind @defer (on viewport), which removes their requests from the initial load entirely. Fetch what is visible in as few round trips as possible, which may mean asking the backend for an aggregate endpoint. And render each panel as its data arrives rather than waiting for all of them, so the page is useful at one second rather than four.
What I would avoid is a single mega-endpoint returning everything, because it becomes the slowest panel's latency for every panel and it fails as a unit.
Land it Progressive rendering is usually worth more than raw speed here — fourteen panels appearing over three seconds feels far better than a blank page for four.
- "When is an aggregate endpoint the right call?"
When the panels are genuinely always shown together and the backend can produce them in parallel more cheaply than the browser can request them — typically because it is co-located with the data.
The cost is coupling: the endpoint now exists to serve one screen's layout, so every layout change is a backend change. A middle option is a gateway that fans out server-side while keeping the panel APIs independent, which is where BFF patterns earn their keep.
Q75. "How would you implement optimistic updates, and what can go wrong?"
Reveal answer
Strong answer Apply the change to local state immediately, send the request, and reconcile when it returns — replacing the optimistic value with the server's, or rolling back on failure.
Concretely: keep the previous state, update the signal, and on error restore it and tell the user the action failed. On success, replace with the server's response rather than keeping the guess, because the server may have normalised or enriched it.
Three things go wrong. Rollback is visually jarring if the user has moved on — an item reappearing in a list they scrolled past is confusing, so the message matters as much as the revert.
Concurrent edits mean the rollback target may itself be stale: two optimistic updates in flight, the first fails, and restoring its snapshot undoes the second as well. Reconciling per-item rather than per-list avoids that.
Server-assigned values — ids, timestamps, computed totals — are not known optimistically, so anything keyed on them must tolerate a temporary client-generated placeholder.
Land it Optimistic updates are right for actions that almost always succeed and are easy to undo — a like, a checkbox, a reorder — and wrong for payments, where a wrong guess is worse than a spinner.
Q76. "How do you cache HTTP responses in Angular, and what invalidation policy would you choose?"
Reveal answer
Strong answer The first question is whether the browser's own HTTP cache can do it, because Cache-Control and ETag headers cost no application code and work across tabs and reloads. For reference data, that is often the whole answer.
When it must be in the application, the options in increasing complexity are: a shareReplay(1) on a per-key observable for the lifetime of a service; a map from request key to resource, so each key has its own value, loading and error signals; or a proper cache with a time-to-live and explicit invalidation on mutations.
For invalidation I would prefer explicit over clever: after a mutation, reload the resources that could have been affected. Time-based expiry alone means a user who just saved something can still see the old value, which is the most confusing possible outcome.
I would also refetch on window focus for data that changes underneath the user, which covers most of the "I switched tabs and it was stale" complaints cheaply.
Land it The rule that keeps this sane is that the client cache must never be stale immediately after the user's own action — everything else is a tuning decision.
Q77. "What is the correct way to handle file uploads with progress?"
Reveal answer
Strong answer Build a FormData, post it with reportUploadProgress: true and observe: 'events', and select the XHR backend with withXhr(), since fetch cannot report upload progress.
The response is then a stream of HttpEvents. I filter for HttpEventType.UploadProgress to compute a percentage from loaded and total, and for HttpEventType.Response to get the final body.
Beyond the mechanics, three things matter for a real feature. Cancellation: unsubscribing aborts the request, and the user needs a cancel button. Concurrency: several files should upload with a bounded mergeMap, not all at once. And validation before sending — type and size checked client-side for a fast error, and again server-side because the client cannot be trusted.
For large files I would move to chunked or resumable uploads, because a single failed 2 GB request means starting over.
Land it Do not set Content-Type manually for FormData — the browser must set it, because it includes the multipart boundary, and overriding it produces a request the server cannot parse.
Q78. "How would you integrate a WebSocket into a signal-based Angular app?"
Reveal answer
Strong answer I would keep the socket in a service, expose the data as signals, and never let components touch the socket directly.
The service opens the connection, and its message handler writes into a signal — that write is what schedules rendering in a zoneless app. Connection state is its own signal, so the UI can show connecting, connected and disconnected honestly.
Three things are easy to get wrong. Reconnection with exponential backoff and a cap, since a tight reconnect loop against a downed server is a denial of service you wrote yourself. Cleanup via DestroyRef so the socket closes, and an onCleanup if it is opened inside an effect keyed by a room or channel. And buffering, because a high-frequency feed must be coalesced to at most one signal write per animation frame rather than one per message.
If the data is a stream of events rather than state, I would expose a Subject alongside the signals, because a signal collapses two identical events into one.
Land it The message rate and the render rate must be decoupled deliberately, or a busy feed turns into a render per message and the tab stops responding.
- "How does this behave under SSR?"
It must not open at all on the server. A socket keeps the application from reaching stability, so the render hangs or times out — and the connection would be pointless anyway, since the result is a static string.
I would open it in
afterNextRenderor behind anisPlatformBrowserguard, and have the server render the loading or last-known state.
Q79. "What security issues live in the HTTP layer of an Angular app?"
Reveal answer
Strong answer Four, and the first two are the ones interviewers press on.
Token storage. A token in localStorage is readable by any script that gets injected, so one cross-site-scripting hole becomes full account takeover. In-memory plus a refresh in an HttpOnly, Secure, SameSite cookie is the stronger arrangement.
Cross-site request forgery. If you authenticate with cookies, a request from another origin carries them automatically. Angular's withXsrfConfiguration reads a token from a cookie and sends it as a header, which works because another origin can cause the cookie to be sent but cannot read it to set the header.
Leaking data in URLs. Query strings end up in server logs, proxy logs and referrer headers, so identifiers and tokens do not belong there.
Trusting the response. Rendering server-supplied HTML through bypassSecurityTrustHtml is a hole regardless of how trusted the server is, because the server may itself be relaying user content.
Land it The framing that lands is that the browser is not a trusted environment: everything in the bundle is public, and every client-side check needs a server-side twin.
Q80. "How do you test HTTP code, including the failure paths?"
Reveal answer
Strong answer With provideHttpClient() plus provideHttpClientTesting(), then HttpTestingController.
expectOne(url) asserts exactly one matching request went out, which catches a wrong endpoint or a duplicate call rather than letting them pass silently. It also returns the request, so I can assert on headers, body and params.
req.flush(body) supplies a success; req.flush(null, { status: 500, statusText: 'Server Error' }) supplies a failure; req.error(new ProgressEvent('error')) simulates a network failure, which is a different path from an HTTP error status.
http.verify() in an afterEach fails the test if any request was left unanswered — which catches calls the component made that the test did not know about.
The failure paths are the ones worth the effort, because they are the branches nobody exercises by hand and the ones users hit on a bad network.
Land it verify() is the underused half: it turns "the test passed" into "the test passed and nothing unexpected was requested".
Mixed scenarios where dependency injection and asynchrony meet — the combinations that produce bugs neither area explains on its own.
Q81 · Scenario. "A service's constructor starts a subscription. Why is that a problem, and when is it not?"
Reveal answer
Strong answer For a providedIn: 'root' service it is usually fine in terms of leaks, because the service lives as long as the tab does. The problems are different ones.
It runs on the server. During SSR the constructor executes, so a subscription to an interval or a socket keeps the app from stabilising and the render hangs.
It runs whether or not it is needed. Root services are created lazily on first injection, so the work starts at an unpredictable moment determined by which component happened to be rendered first.
It is untestable in isolation. Constructing the service in a unit test starts real work, so every test needs the subscription's dependencies stubbed.
For a route- or component-provided service, add a genuine leak risk: the instance is destroyed but a subscription to a longer-lived source keeps it alive.
My preference is an explicit start() called by whoever needs it, or lazily on first read, with DestroyRef.onDestroy for cleanup.
Land it Constructors should wire dependencies, not start work — that one rule fixes the SSR hang, the test awkwardness and the unpredictable start time together.
Q82. "What is DestroyRef and where does it help beyond components?"
Reveal answer
Strong answer DestroyRef is an injectable handle to the destruction of whatever injection context you are in — a component, a directive, or a scoped service. inject(DestroyRef).onDestroy(fn) registers cleanup.
Beyond components it matters in two places. A service provided on a route or a component has a real destruction moment but no lifecycle hook you would naturally reach for; DestroyRef gives it one.
And in standalone functions — a helper that sets up an observer or a listener can register its own cleanup without the caller having to remember, which makes the helper safe to use anywhere.
It is also what takeUntilDestroyed() uses internally, which is why that operator needs an injection context or an explicit DestroyRef argument.
Land it The value is co-location: setup and teardown in the same few lines, rather than teardown in a method fifty lines away that people forget to update.
Q83 · Scenario. "Two components both call load() on a service at the same time and two identical requests go out. Fix it."
Reveal answer
Strong answer This is request coalescing, and the fix is to share the in-flight observable rather than starting a second one.
The service keeps a field for the current request. load() returns it if one exists, otherwise creates it with shareReplay(1) and stores it, clearing the field when it settles so a later call refetches.
With resources the problem largely disappears, because a resource is a single object both components read rather than a method each calls.
The design point underneath is that a method returning a cold observable will always do this — every subscriber gets its own execution. If the service is meant to own a single shared value, it should expose a signal or a resource, not a method that produces a new request per caller.
Land it Expose state, not fetchers: a service handing out cold observables makes every consumer responsible for deduplication, and they will not all remember.
Q84. "How do route resolvers work, and would you use one?"
Reveal answer
Strong answer A resolver is a function the router runs before activating a route; navigation waits for it, and its result is available to the component through the route data or as an input with component input binding.
The advantage is that the component renders with its data already present, so there is no loading state and no flash of an empty screen.
The disadvantage is that the user stares at the previous page while it runs, with no feedback unless you wire up the router's navigation events to a progress bar. A slow resolver feels like a broken link.
My preference in most cases is to navigate immediately and let the component show its own loading state with a resource, because partial feedback beats none. I would use a resolver when the page is meaningless without the data and a wrong render would be worse — for instance when a 404 should redirect rather than render an empty detail page.
Land it Resolvers move the wait from inside the page to before it, which is only an improvement if you also show that the wait is happening.
Q85. "What is the difference between canActivate, canMatch and canActivateChild?"
Reveal answer
Strong answer canActivate runs after the route has been matched and, for a lazy route, after its bundle has been downloaded. It decides whether to activate.
canMatch runs during matching, before the lazy chunk is fetched. If it returns false the router treats the route as not matching at all and continues to the next one in the array.
canActivateChild runs for every child route under the one it is declared on, which avoids repeating the same guard on ten children.
Two consequences follow. For an admin area, canMatch is better than canActivate, because a non-admin never downloads the admin code — it stays off their machine entirely.
And because a failed canMatch falls through to the next route, you can serve two different components at the same path depending on a role or a feature flag, which canActivate cannot do.
Land it None of them is security — they run in code the user controls. They are user experience and bundle hygiene, and the server enforces the actual rule.
Q86. "How would you implement 'unsaved changes' protection properly?"
Reveal answer
Strong answer Two mechanisms, because neither covers the other's case.
A canDeactivate guard covers navigation inside the application. It receives the component instance, so it can ask whether the form is dirty and return a confirmation.
A beforeunload listener covers closing the tab, reloading, or typing a new URL — none of which go through the router. The browser shows its own generic dialog and you cannot customise the text.
Two refinements matter in practice. Dirty should mean "the user changed something meaningful", not "a control emitted", or focusing and leaving a field triggers a warning and people learn to click through prompts.
And an autosaved draft is usually a better product answer than a prompt: saving to local storage and restoring on return removes the decision from the user entirely.
Land it A prompt that fires when nothing meaningful changed trains users to dismiss it, which makes the real warning useless.
Q87 · Scenario. "An interceptor shows a global spinner on every request. Users complain the page 'flashes'. Fix it."
Reveal answer
Strong answer Three problems are usually present together.
No delay. A request that completes in 80 ms shows and hides a spinner faster than the eye resolves, which reads as a flicker. Only show the indicator after about 150 ms.
No minimum duration. Once shown, it should stay for at least a few hundred milliseconds, or a fast response produces the same flash at the other end.
No exclusions. Background polling, analytics and prefetching should not drive a global indicator at all — that is what HttpContext tokens are for, so a request can opt out.
I would also question the design. A global spinner is a blunt instrument; a local indicator next to the thing that is loading tells the user what is happening, and keeping stale content visible with a subtle progress bar is better still.
Land it The delay-plus-minimum pair is the whole trick, and it is exactly what @defer's @loading (after …; minimum …) encodes for the deferred case.
Q88. "How do you share state between a parent route and its children?"
Reveal answer
Strong answer By providing a service in the parent route's providers array. Every child under that route resolves to the same instance, and it is destroyed when the user leaves the subtree.
That is the right lifetime for feature state: a multi-step wizard, a shared filter across sibling tabs, a loaded aggregate several children display parts of.
The alternatives are worse for this case. A root service works but never resets, so re-entering the feature shows stale state. Passing data through route data or resolvers gives a snapshot rather than something children can update.
The thing to be aware of is that the instance really is destroyed on leaving, so anything expensive is refetched on return. If that matters, cache above it in a root service and let the scoped one hold only the volatile parts.
Land it Route-scoped providers are the most under-used part of Angular's DI, and they are exactly the tool for state that should reset when a feature is left.
Q89. "What happens to in-flight requests when a user navigates away?"
Reveal answer
Strong answer It depends entirely on what holds the subscription, and that is the point of the question.
If the component subscribed with takeUntilDestroyed, the async pipe, toSignal or a resource, destruction unsubscribes and the browser aborts the request.
If the component subscribed bare, nothing cancels it. The request completes, the callback runs against a destroyed component, and it writes to state nobody reads — or throws because something it references was torn down.
If a root-level service holds it, it continues by design, which is correct for a save that should finish regardless of navigation.
The design decision worth stating: reads should be cancelled on navigation, because their results are no longer wanted, while writes should generally complete, because abandoning them leaves the user unsure whether their change was saved.
Land it Cancel reads, complete writes — and that difference is exactly why a save belongs in a service and a fetch belongs in the component's resource.
Q90 · Design. "Design the authentication layer for a large Angular application."
Reveal answer
The real test Whether you keep the browser out of the trust boundary.
Strong answer I would build it from five pieces and be explicit that only one of them is security.
An AuthService holding the current user and authentication state as signals, with the access token in memory rather than localStorage, so an injected script cannot read it.
A refresh token in an HttpOnly, Secure, SameSite cookie, which JavaScript cannot read at all, with the refresh endpoint exchanging it for a new access token.
An interceptor that attaches the access token, and on a 401 performs a single shared refresh with the stampede protection from Q68, retrying the original request.
Guards — canMatch on feature areas so unauthorised users never download the code, redirecting to login with a returnUrl.
Server-side authorisation on every endpoint, derived from the token the server validates. This is the only part that actually enforces anything; everything above it is user experience.
Beyond that: log out on refresh failure rather than looping, clear state on logout including any caches, and handle the multi-tab case so logging out in one tab does not leave another showing private data.
Land it The sentence that decides this round is that the frontend's job is to make the right thing convenient, and the backend's job is to make the wrong thing impossible.
- "Why not put the access token in
localStorage? Everyone does." Because
localStorageis readable by any script running on the origin, so a single cross-site-scripting hole — in your code or in a dependency — becomes a stolen session that outlives the page.In memory, the token dies with the tab and is not reachable by a script that runs later. The refresh cookie being
HttpOnlymeans the same script cannot silently mint new tokens either.The honest cost is that a page refresh loses the access token and needs a silent refresh round trip on startup, which is a small amount of complexity for a large reduction in blast radius.
- "How do you handle logout across tabs?"
Broadcast it. Writing a logout marker to
localStoragefires astorageevent in other tabs, or useBroadcastChannelfor a cleaner API; each tab clears its state and redirects.The server side matters too: the refresh token must be revoked, or another tab simply refreshes itself back into a session. Client-side broadcast without server-side revocation is theatre.
Q91. "What is an InjectionToken with a factory, and why is that useful?"
Reveal answer
Strong answer new InjectionToken<T>('NAME', { providedIn: 'root', factory: () => … }) gives the token a default value produced by a factory, so it needs no provider entry at all.
Two benefits. It is tree-shakeable for the same reason providedIn is — nothing references it unless something injects it. And it makes the token usable with zero configuration, while still being overridable by a provider when someone needs to.
The factory runs in an injection context, so it can itself use inject() to derive its value from other services — for instance a token whose default reads the document's locale or a configuration service.
This is how Angular's own tokens such as DOCUMENT and LOCALE_ID work: a sensible default that you can replace for testing or for a non-browser platform.
Land it Default-with-override is the right shape for library configuration: it works out of the box and is still a seam.
Q92 · Scenario. "A third-party library needs to be initialised once with a key from your API. Where does that go?"
Reveal answer
Strong answer It depends on whether the application can render without it, and that is the question I would ask first.
If nothing can render meaningfully without it — an authentication provider, a configuration service — then an app initialiser, accepting that it delays first paint by the length of that request.
If only some features need it — a maps library, an analytics vendor, a payment widget — then lazily, on first use, behind a service that returns a shared promise so concurrent callers do not initialise twice. Combined with @defer, the library's code is not even downloaded until needed.
What I would avoid is initialising in a component's constructor, because it then depends on which component happens to render first and runs during SSR.
The key itself must come from configuration rather than being compiled in, and it must be a publishable key — anything in the bundle is public, so a secret key belongs on the server with the browser calling through your own endpoint.
Land it The initialiser is time every user pays for; lazy initialisation is time only the users of that feature pay for, and most third parties belong in the second group.
Q93. "How do you debug 'NG0201: No provider for X' in a large application?"
Reveal answer
Strong answer The error means the search walked the element chain, then the environment chain, and reached the NullInjector. So the question is always which chain it was walking and where the provider actually is.
Four checks in order. Does the service have @Injectable({ providedIn: 'root' })? Is a required provide* call missing from app.config.ts — provideHttpClient, provideRouter, provideAnimations are the usual suspects?
Is the provider on a route or component that the injecting code is not actually inside — a common outcome when a component is moved or reused elsewhere?
And in tests, has TestBed.configureTestingModule included it, since the test injector starts empty and inherits nothing from the application.
Angular DevTools' injector tree view makes this visual: it shows which injector a component resolved against and what each one provides, which turns a guess into a lookup.
Land it Most instances in real codebases are the third case — the component moved, and the provider it depended on did not move with it.
Q94. "What is the right way to expose a service's state to components?"
Reveal answer
Strong answer A private writable signal, a public read-only view via asReadonly(), derived values as computed, and a small named set of methods that are the only writers.
The reason is not purity, it is debugging. When a value is wrong, the number of places it could have been written is the number of methods on the service — typically three or four — rather than every component that injected it.
Deriving rather than storing matters just as much. A count kept as a second signal must be maintained everywhere the list changes; a count as a computed cannot fall out of step because there is no line to forget.
What I would not expose is the writable signal itself, or a method that returns the internal array, because both hand out the ability to mutate shared state from anywhere.
Land it This one line — asReadonly() — is the highest-value habit in signal-based Angular, and it costs nothing.
Q95 · Scenario. "Your app works locally and throws NG0203 in production only. What could differ?"
Reveal answer
Strong answer NG0203 is inject() called outside an injection context, and a difference between environments points at timing or build configuration rather than at the call itself.
The likeliest causes are ordering: in production, code is minified and modules may be evaluated in a different order, so a class referenced before its declaration behaves differently — the case forwardRef exists for.
Another is that a code path only taken in production — a feature flag, a different route, an error handler — calls inject() from a callback. It was always wrong; local testing never reached it.
A third is duplicate copies of @angular/core in the dependency tree, so the ambient context variable one copy sets is not the one the other reads. That shows up with a mis-hoisted dependency or a library bundling its own Angular.
I would confirm the third with npm ls @angular/core, and the first two by reading the stack trace from a source-mapped build rather than the minified one.
Land it Two copies of the framework is the one people never suspect, and it explains a whole family of "impossible" injection and instanceof failures.
Q96. "What does @Service() add in Angular 22?"
Reveal answer
Strong answer It is a shorter spelling of the overwhelmingly common case. @Service() means the same as @Injectable({ providedIn: 'root' }), and @Service({ autoProvided: false }) covers the case where you provide it yourself somewhere.
The value is that the default becomes the short form, which nudges people toward root provision and away from the component-level providers array that causes the duplicate-instance bug.
It changes no behaviour, and @Injectable continues to work — which matters, because every existing codebase and every existing answer uses it.
I would use whichever a team has standardised on and not make it a review topic.
Land it Knowing the long form is what makes the short one obvious, so learning order should be @Injectable first regardless of which you write.
Q97. "How would you structure services in a feature so they stay testable?"
Reveal answer
Strong answer By separating three responsibilities that people routinely put in one class.
An API client that knows URLs and response shapes and nothing else. It has no state, so testing it is asserting on requests with HttpTestingController.
A store that holds signals and the rules for changing them. It has no HTTP, so testing it is constructing it with new and asserting on signals — no TestBed, no async, milliseconds per test.
A facade or the components themselves coordinating the two: call the API, put the result in the store, handle the failure.
The payoff is that the store, which holds the business rules and is where the bugs are, becomes trivially testable. Merging HTTP into it means every rule test needs a stubbed network.
I would not add a facade layer by default — it is often ceremony — but the API-versus-store split earns its keep in any feature with real logic.
Land it The test for the split is whether the business rules can be tested without a network stub; if not, they are tangled with transport.
Q98. "How do you handle an API whose response shape you do not control?"
Reveal answer
Strong answer Validate and map at the boundary, and never let the external shape leak into the application.
Concretely: the API client parses the response with a runtime validator such as Zod, then maps it into an internal model the rest of the code uses. A shape change then fails at the edge with a clear message naming the field, rather than as an undefined three components away.
The mapping also insulates you from the API's naming and structure, so when it changes there is one file to update rather than fifty templates.
For genuinely optional or evolving fields I would model them explicitly as optional in the internal type, so the compiler forces every consumer to handle absence rather than assuming.
And I would log validation failures to monitoring, because an upstream change is something you want to know about on the day it ships rather than from a user.
Land it http.get<T>() is a claim, not a check — treating it as a check is how a silent upstream change becomes a support ticket a week later.
Q99. "What is the cost of a badly scoped service in a long-running application?"
Reveal answer
Strong answer Two costs, in opposite directions.
Scoped too widely — a root service holding what should be per-screen state. Memory grows, because caches and arrays accumulate for the lifetime of the tab. And behaviour is wrong: leaving a screen and returning shows stale state, and two instances of the screen share data they should not.
Scoped too narrowly — a shared store in a component's providers. Instances multiply, each holding a fraction of the truth, and the symptom is a screen where one panel updates and its neighbour does not.
The first is a slow leak, the second is an immediate correctness bug, and the second is easier to find precisely because it is immediate.
The diagnostic for both is the same: log identity from two injection sites, and take a heap snapshot across ten navigations to see whether instances accumulate.
Land it "How many of these should exist, and when should they die" is a design question worth answering explicitly for every service, because the default answer is rarely reconsidered.
Q100 · Design. "Design a data layer for an offline-capable Angular application."
Reveal answer
Strong answer Four layers, and the hard part is not any of them individually — it is the conflict policy.
Local storage as the source of truth for reads. IndexedDB holds the data; the UI reads from it, so the application works identically online and offline. The network is a synchroniser, not a dependency.
An outbox for writes. Every mutation is appended to a queue with a client-generated id, applied locally immediately, and sent when connectivity allows. This is the same pattern as the transactional outbox in E7, applied in the browser.
A sync engine that drains the outbox in order, retries with backoff, and pulls server changes since a cursor. It must be idempotent, because a request may have succeeded before the connection dropped and will be retried.
A service worker for the application shell, so the app itself loads offline. Angular's service worker package handles the assets; the data layer is separate and yours.
The conflict policy is the product decision. Last-write-wins is simple and loses data. Per-field merge is better where fields are independent. Anything genuinely contended needs the user to choose, which means the model must be able to hold two versions at once.
I would also be honest that offline support roughly doubles the complexity of the data layer, so it should be a requirement rather than a nice-to-have.
Land it The decision that shapes everything is making local storage the read source rather than a cache in front of the network — that is what makes offline a mode rather than a special case.
- "How do you handle ids for records created offline?"
Generate them on the client — a UUID — and have the server accept the client's id as the primary key, or return a mapping the client applies when the record syncs.
The second is harder than it sounds, because anything that referenced the temporary id must be rewritten, including other queued writes. Accepting client-generated ids server-side is usually worth negotiating for.
- "How do you know the app is actually offline?"
navigator.onLineis unreliable — it reports whether there is a network interface, not whether your server is reachable, so a captive portal reads as online.The honest signal is request failure: attempt the sync, and treat repeated network-level failures as offline with backoff. The
onlineandofflineevents are useful as a hint to retry sooner, not as truth.
11 · DrillForms, Routing, State & Testing — Q101–Q150
This block is the application layer: the parts of Angular you touch every day and are therefore expected to have opinions about.
Interviewers use these questions differently from the internals ones. They are less about whether you know the mechanism and more about whether you have maintained something — whether you can say what you would do differently, and why.
If you have worked on enterprise software, forms are most of what you have built. These fifteen cover the reactive API, validation design, and the cases that make forms genuinely hard.
Q101. "Reactive versus template-driven versus Signal Forms — pick one and defend it."
Reveal answer
Strong answer Reactive for anything real, and I would give three reasons rather than a preference.
The form is an object in TypeScript, so it is typed, and with nonNullable groups getRawValue() returns exactly the shape the service expects.
It is testable without rendering: I can construct the group, set values and assert on validity in a unit test that runs in milliseconds.
And dynamic structure is straightforward — adding rows, conditional sections, cross-field rules — where template-driven forms make each of those awkward.
Template-driven is acceptable for a two-field filter bar where a form object is overkill. Signal Forms, stable in Angular 22, are the direction of travel: the model is a signal and the form is a view over it, so there is one source of truth instead of a form object plus a copy.
Land it I would learn reactive forms first regardless, because they are in every existing codebase, and adopt Signal Forms for new features with compatForm() to migrate incrementally.
- "What specifically do Signal Forms improve?"
The duplication. In reactive forms the
FormGroupholds the values and the component usually holds a model too, and keeping them aligned — patching on load, reading on submit — is a familiar chore that goes wrong at the edges.With
form(modelSignal, schema)the model is the form's value, so there is no synchronisation step, and validation state is signals like everything else rather than an observable API you have to bridge.
Q102. "How do you design validation for a form with cross-field rules?"
Reveal answer
Strong answer Field rules go on the control; rules involving two fields go on the group that contains both, because that is the only place with access to both values.
A group validator receives the group and returns null or an error object — for instance a date-order rule comparing start and end.
The presentation problem is where the message appears. A group error is not attached to either field, so it needs its own place in the template, usually near the pair it concerns rather than at the top of the form.
The subtlety people miss is when to show it. A start-after-end error while the user is midway through changing both dates is noise. I would show group errors on blur of the second field or on submit, not on every keystroke.
Land it Validation design is as much about timing as about rules — a correct message shown at the wrong moment is experienced as the form being broken.
- "Where do you put the same rules the server enforces?"
Both places, deliberately, and I would say why. The client's copy exists for fast feedback; the server's exists because the client cannot be trusted.
The risk is drift, so where the rules are non-trivial I would generate the client validators from a shared schema, or at minimum keep them in one module with tests that encode the same examples as the server's tests.
Server errors must also be mappable back onto fields, which means the API should return field-keyed errors rather than a single message.
Q103. "How do async validators work and what do you watch out for?"
Reveal answer
Strong answer An async validator returns an observable or promise of the error object or null. While it runs the control's status is PENDING, and the form is not valid during that time.
Three things to watch. They run on every value change by default, so a username check hits the server per keystroke — the validator itself must debounce, since Angular does not.
Only after the sync validators pass, which is good: no server call for an empty or malformed field.
The submit button must account for PENDING. Disabling on invalid alone lets a user submit while a check is still running; disabling on invalid || pending means the button flickers as they type. I usually keep it enabled and handle pending in the submit handler by awaiting the check.
And the server must re-check regardless, because a uniqueness check that passed a second ago can be false by the time the form is submitted.
Land it An async uniqueness check is a hint, never a guarantee — the race between checking and submitting is real, and only a server-side constraint closes it.
Q104 · Scenario. "A form with 60 fields is sluggish while typing. Diagnose."
Reveal answer
Strong answer Five candidates, checked in this order.
A subscription to the whole group's valueChanges doing real work. Every keystroke in any field emits the entire form value, and if the handler recalculates something across all 60 fields, that is the cost. Subscribe to individual controls, or debounce.
Validators that are expensive, particularly regular expressions with catastrophic backtracking, running on every change of every field.
A method or getter in the template computing something per field — hasError(...) called across 60 fields on every check is 60 calls per render.
The whole form re-rendering because it is one large component with no OnPush boundaries. Splitting into section components gives skip points.
updateOn timing. Switching a control or the group to updateOn: 'blur' means validation runs once per field visit rather than per character, which for a large form is often the single biggest win.
Land it updateOn: 'blur' is the underused lever here — it changes the validation frequency by two orders of magnitude and usually improves the experience as well.
Q105. "How do you build a dynamic form from a server-supplied schema?"
Reveal answer
Strong answer The schema describes fields — key, label, type, validators, visibility conditions. A builder walks it and constructs a FormGroup with the right controls and validator functions.
Rendering is a @switch on the field type mapping to input components, or dynamic component creation if the set is genuinely open.
Three hard parts. Validator mapping: the schema names rules as strings, so you need a registry from name to validator factory, and an unknown rule must fail loudly rather than silently not validating.
Conditional visibility: a field shown only when another has a value. Hidden fields should be disabled or removed, or they contribute validation errors the user cannot see or fix — a form that will not submit with no visible reason.
Typing: the form's value is not statically known, so the type safety that makes reactive forms attractive is gone. I would validate the resulting payload at the boundary to get some of it back.
Land it The invisible-invalid-field problem is the one that generates support tickets, and it is worth designing for explicitly rather than discovering.
Q106. "What is ControlValueAccessor and when have you implemented one?"
Reveal answer
Strong answer It is the interface that lets a custom component participate in Angular's forms API — so formControlName works on your component exactly as it does on an <input>.
You implement four methods: writeValue when the form pushes a value in, registerOnChange to get a callback for pushing values out, registerOnTouched for blur, and setDisabledState so disable() works.
I have implemented it for things a native input cannot express: a currency field with formatting, a tag picker, a date range, a rating control.
The one people forget is setDisabledState, and its absence is a subtle bug — the form thinks the control is disabled, the component still accepts input, and the value the user typed is silently dropped from value.
Land it The whole point is that the rest of the application should not know the control is custom — anything that leaks that fact is an incomplete implementation.
- "How does it interact with
OnPush?" Carefully.
writeValueis called by the forms system, not by an input binding or an event, so on anOnPushcomponent nothing marks it dirty and the new value does not render.The classic fix was
markForCheck()insidewriteValue. The better modern fix is to store the value in a signal, so the write itself schedules the render.
Q107. "How do you handle server-side validation errors coming back on submit?"
Reveal answer
Strong answer The API should return field-keyed errors — a map from field name to message — and the client should apply them onto the matching controls with setErrors.
That puts each message next to its field, which is where the user is looking, rather than in a banner at the top that they have to map back themselves.
Two details matter. Server errors must be cleared when the user edits the field, or a corrected value still shows the old complaint; subscribing to that control's valueChanges once to clear the server error does it.
And errors that do not map to a field — "this order can no longer be modified" — need a form-level place to appear, and must not be lost.
I would also focus the first field with an error, because on a long form the user may not see a message below the fold.
Land it A field-keyed error contract is something to negotiate with the API early, because retrofitting it means parsing prose messages.
Q108. "Explain FormArray and when you would use it."
Reveal answer
Strong answer A FormArray is a control containing an ordered list of controls, addressed by index rather than by name. It is the right structure for a repeating section — invoice lines, phone numbers, passengers on a booking.
You render it with formArrayName on the container and [formGroupName]="i" on each row, and mutate it with push, removeAt and insert.
Two practical points. Removing by index while iterating is the usual bug: capture the index at the time of the click and remove once, since the array shifts underneath.
And the @for over its controls needs a track that is not the index, or removing a middle row destroys and rebuilds every row after it — losing focus and any component state in them. Tracking by a stable id on the row's own value is the fix.
Land it The index-tracking problem in a FormArray is exactly the list-identity problem from the rendering block, wearing a forms hat.
Q109. "What is the difference between disable() and the disabled attribute in reactive forms?"
Reveal answer
Strong answer In reactive forms, disabled state belongs to the control, not to the template. Calling control.disable() sets it; binding [disabled] on the input alongside formControlName produces a warning and fights the form model.
The consequences of disabling are two. The control's value is excluded from form.value, which surprises people at submit time — a derived or read-only field silently disappears from the payload. getRawValue() includes it.
And a disabled control's validators do not run, so it cannot make the form invalid. That is usually what you want and occasionally not.
If the intent is "visible but not editable" rather than "not part of this form", readonly on the input is often the better choice, because the value stays in value and the field stays focusable for screen readers.
Land it "The field shows a value and the server receives nothing" is nearly always disable() plus form.value, and it is a five-second fix once you know it.
Q110. "How would you make a large form accessible?"
Reveal answer
Strong answer Five things, and none of them are Angular-specific, which is the point.
Every control has a real <label for>. Placeholder text is not a label — it disappears on focus and is invisible to some assistive technology.
Errors are connected with aria-describedby pointing at the message element, and the control is marked aria-invalid, so a screen reader announces the problem rather than just "invalid".
Related controls are grouped in a <fieldset> with a <legend>, which is how a radio group communicates what it is asking.
On failed submit, focus moves to the first invalid field, and an error summary is announced in a live region — otherwise a keyboard user has no idea anything happened.
And required-ness is conveyed with the required attribute rather than only an asterisk in the label text.
Land it The submit case is the one most often missed: a form that silently fails to submit is completely opaque without sight of the red text.
Q111 · Scenario. "Users report losing a long form when their session expires. Design the fix."
Reveal answer
Strong answer Three layers, and I would ship them in this order because each is independently useful.
Do not lose the data. Autosave a draft to localStorage on a debounced valueChanges, keyed by form and user, and restore it on return. That makes every subsequent failure recoverable regardless of cause.
Do not lose the session silently. Refresh the token in the background before it expires rather than reacting to a 401 at submit time, so an active user's session does not lapse while they type.
Handle the failure gracefully. If the submit does return 401, keep the form state in memory, prompt for re-authentication in a dialog rather than navigating away, and resubmit afterwards.
What I would avoid is a redirect to a login page on 401 from a form submit, which is what causes the reported loss — the component is destroyed and the data goes with it.
I would also clear the draft on successful submit, or the user sees stale data next time and does not know whether it was saved.
Land it Autosave first, because it fixes session expiry, accidental navigation, a closed tab and a browser crash with one mechanism.
Q112. "What does updateOn do and when would you change it?"
Reveal answer
Strong answer It controls when a control's value and validity update: 'change' by default, or 'blur', or 'submit'. It can be set per control or for a whole group.
I change it to 'blur' for two reasons. Performance, on large forms where validation per keystroke is measurable. And experience, for fields where per-character validation is hostile — an email field showing "invalid email" after the first letter is noise.
'submit' is right for a form where nothing should be judged until the user says they are finished, though it delays all feedback to one moment.
The trade-off is that valueChanges also only fires on blur, so anything relying on live values — a character counter, a live preview — stops working and must read the raw input instead.
Land it It is one of the highest-leverage options in reactive forms and one of the least used, because it is set at construction and never revisited.
Q113. "How do you test a reactive form well?"
Reveal answer
Strong answer In two layers, because they catch different things.
Without rendering, for the rules: construct the form, set values, assert validity and specific error keys. These are fast, they cover the combinations exhaustively, and they are where I would put the effort — validation rules encode requirements, and requirements change.
With rendering, for the behaviour: does the error appear only after touch, is submit disabled when invalid, does markAllAsTouched reveal everything on a failed submit, does the emitted payload match what the service expects.
I would assert on error keys rather than on message text, so wording changes do not break the suite, and I would have at least one test per validation rule using the exact examples from the requirement.
The case worth an explicit test is the disabled-control-excluded-from-value behaviour, because it is a silent data-loss bug that no other test catches.
Land it Form logic is the cheapest thing in a frontend to unit test and among the most valuable, because it is where the business rules actually live.
Q114. "What are typed forms and what did they change?"
Reveal answer
Strong answer Before Angular 14, form.value was any. Every read was unchecked, so a renamed field failed silently at runtime.
Typed forms infer the shape from the builder call, so form.controls.title is a FormControl<string> and getRawValue() returns a properly typed object.
The wrinkle is nullability. By default a control's type includes null, because reset() sets controls to null. fb.nonNullable.group(...) changes that: reset returns each control to its initial value instead, and the types lose the null.
The other wrinkle is that dynamic forms lose most of the benefit, since the shape is not statically known — FormRecord exists for the homogeneous case where keys vary but the control type does not.
Land it Use nonNullable by default; the null in every control's type is a historical artefact that leaks into every consumer.
Q115 · Design. "Design a multi-step wizard with validation, back navigation and a resumable draft."
Reveal answer
Strong answer I would make three decisions explicitly.
One form or several? One FormGroup containing a nested group per step. That keeps cross-step validation possible, makes the whole payload available at any point, and means back navigation is just rendering a different section — no state transfer between steps.
Where does step state live? In a service provided on the wizard's route, so it is shared by every step component and destroyed when the user leaves the feature. Root would leak between visits; component-level would not survive step navigation.
Are steps routes or a switch? Routes, so the browser's back button and deep links work — users will press back, and a wizard that treats it as leaving the flow is infuriating. Each step is a child route with a guard that redirects to the first incomplete step, so someone cannot deep-link into step four with empty data.
On top of that: autosave the draft to storage on a debounced value change and restore on return; a canDeactivate guard for leaving the flow entirely; and a review step showing everything with links back to each section.
Submission is one call at the end if the backend supports it, or a draft resource created up front and patched per step if steps must persist independently — and that is a backend conversation, not a frontend decision.
Land it The two decisions that make or break it are one form rather than five, and steps as routes rather than a switch — both are hard to retrofit once the wizard exists.
- "How do you stop a user skipping ahead by editing the URL?"
A
canActivateguard per step that checks whether the preceding steps' groups are valid, redirecting to the first incomplete one if not.And the server must validate the whole payload on submit regardless, because the guard is client-side and therefore advisory. If a step exists to gate something meaningful — a payment, an eligibility check — the server has to enforce it.
Routing questions are really URL-design questions, and the senior signal is treating the address bar as application state rather than as decoration.
Q116. "What belongs in the URL and what does not?"
Reveal answer
Strong answer Anything a user would reasonably expect to survive a refresh, be restorable with the back button, or be shareable as a link.
That means: which record is open, the current page, the sort column and direction, active filters, the selected tab, and a search term.
It does not mean: transient UI state such as whether a dropdown is open or which row is hovered; anything sensitive, because URLs end up in server logs, proxy logs and referrer headers; and anything large, since URL length limits are real.
The payoff for getting this right is that three recurring bug reports — "refresh loses my filters", "back button goes to the wrong place", "I can't send my colleague this view" — stop being bugs and become features, for the cost of one withComponentInputBinding() line.
Land it The URL is the only piece of application state the user can edit, bookmark and share, which makes it the most valuable place to keep anything they care about.
- "How do you update query params without polluting the history?"
router.navigate([], { queryParams, queryParamsHandling: 'merge', replaceUrl: true }). ThereplaceUrlflag replaces the current history entry rather than pushing a new one.That matters for continuous changes: without it, typing ten characters into a filter creates ten history entries and the back button walks the user through their own typing.
I would use
replaceUrlfor filter and search changes, and a normal push for discrete navigations like changing page or opening a record.
Q117. "How does withComponentInputBinding work and what did it replace?"
Reveal answer
Strong answer Enabled in provideRouter, it binds route parameters, query parameters, resolved data and static route data to component inputs by matching names.
It replaced injecting ActivatedRoute and reading either snapshot.params or the params observable.
The snapshot version had a well-known bug: the router reuses a component when only parameters change, so a constructor that read the snapshot once kept showing the first record forever when navigating from /tasks/42 to /tasks/99.
The observable version was correct but needed a subscription and its cleanup, and put the data flow in an imperative callback.
With input binding the parameter is a signal, so a reused component simply sees a new value and anything derived from it — including a resource's URL — recomputes with no lifecycle awareness at all.
Land it It converts the most common routing bug in Angular's history from something you must remember into something that cannot happen.
Q118. "Explain route matching order and the traps in it."
Reveal answer
Strong answer The router walks the routes array from the top and takes the first path that matches. It is not most-specific-wins, which is what people assume.
Three traps follow. The wildcard '**' must be last, or it swallows everything below it and every route after it becomes dead code.
A static segment must come before a parameterised one at the same level: tasks/new before tasks/:id, or new is matched as an id and the page tries to load a record called "new".
And redirectTo on an empty path needs pathMatch: 'full'. The default is prefix matching, and an empty path is a prefix of every URL, so it redirects everything and usually loops.
Child routes are matched within their parent's remaining segments, and a failed canMatch causes the router to continue to the next route rather than fail — which is how you serve different components at one path by role.
Land it Reading a routes array as a priority list rather than a set makes all three traps obvious rather than surprising.
Q119. "What are auxiliary routes and have you used them?"
Reveal answer
Strong answer They let several independent outlets be active at once, each with its own route, encoded in the URL as (outletName:path).
The use case is a secondary region whose state should be in the URL independently of the main one — a detail panel beside a list, a chat sidebar, a persistent player.
I have used them rarely, and I would be honest about why. The URL syntax is unusual and users find it strange when they see it; the API for constructing those links is fiddly; and guards and resolvers on auxiliary routes interact with the primary in ways that are easy to get wrong.
For most detail-panel cases a query parameter is simpler and gives the same shareability — ?selected=42 is easier to read, easier to link and easier to reason about than an auxiliary outlet.
Land it They are the correct answer to a real problem and usually not the best one, which is worth saying rather than pretending they are widely used.
Q120 · Scenario. "Navigating between two tabs of the same feature loses scroll position. Fix it."
Reveal answer
Strong answer First I would check withInMemoryScrolling, which is not on by default. { scrollPositionRestoration: 'enabled' } restores position on backward navigation and scrolls to top on new navigations, and anchorScrolling: 'enabled' makes fragment links work.
That handles the browser-history case. It does not handle a forward navigation between tabs where the user expects the position kept, because the router treats it as a new page.
For that I would ask whether the tabs should be separate routes at all. If the content is the same list with a filter, a query parameter keeps one component mounted and there is no scroll to restore.
If they genuinely are separate routes with separate components, the options are storing scroll position per route in a service and restoring it in afterNextRender, or a RouteReuseStrategy that detaches and reattaches the component tree.
I would reach for the reuse strategy last, because it keeps subscriptions alive in detached trees and is an easy way to introduce a leak.
Land it Half of scroll-restoration problems disappear by asking whether those really need to be two routes.
Q121. "How do you handle a 404 for a record that does not exist, as opposed to a route that does not exist?"
Reveal answer
Strong answer They are different situations and should look different to the user.
A route that does not exist is matched by the wildcard route and renders a not-found page. Nothing was fetched; the URL is simply wrong.
A record that does not exist is a successful navigation whose data request returned 404. The right response is usually to render the detail page's shell with a clear "this task no longer exists" message and a link back to the list — not to redirect, because a redirect hides what happened and loses the URL the user might want to correct.
The exception is when the URL should not remain in history, for instance after a deletion, where replacing the history entry avoids the back button returning to a dead record.
If server-side rendering is on, the record case should also set a 404 status code on the response, or search engines index a "not found" page as if it were content.
Land it The status-code point is the one that separates people who have shipped SSR: a soft 404 rendered with a 200 is an SEO problem nobody notices for months.
Q122. "What is preloading and how would you configure it for a large app?"
Reveal answer
Strong answer Preloading downloads lazy chunks in the background after the initial page is interactive, so the first navigation to a lazy route is instant while the initial bundle stays small.
withPreloading(PreloadAllModules) fetches everything, which is fine for a small application and wasteful for a large one — a user who visits two of twenty features downloads all twenty.
For a large app I would write a custom strategy driven by route data: mark the two or three routes users actually go to next with data: { preload: true } and preload only those.
I would also make it conditional on the network. The Network Information API exposes an effective connection type and a data-saver flag, and preloading twenty chunks on a metered mobile connection is hostile.
The alternative worth mentioning is @defer with prefetch on hover for in-page navigation, which targets the specific thing the user is about to click.
Land it Preloading everything is a default rather than a decision; the question is which two routes are worth the bandwidth for this product.
Q123. "How do you show a loading indicator during navigation?"
Reveal answer
Strong answer Subscribe to the router's event stream and track NavigationStart against the terminal events — NavigationEnd, NavigationCancel and NavigationError.
The three terminal events matter: handling only NavigationEnd leaves the indicator spinning forever when a guard cancels the navigation, which is a common bug and looks like a hang.
The same delay-and-minimum rules from the HTTP spinner question apply — show after roughly 150 ms, keep for a few hundred, or fast navigations flash.
The stream never completes, so it needs takeUntilDestroyed or, better, toSignal over a mapped boolean so the template reads a signal.
What this indicator covers is chunk download and guard or resolver time. Data loaded inside the component is the component's own loading state, and conflating the two produces a bar that disappears while the page is still empty.
Land it Forgetting NavigationCancel is the specific bug here, and a guard that redirects is the most common way to trigger it.
Q124. "What is the difference between routerLink with a string and with an array?"
Reveal answer
Strong answer The string form is a literal path — routerLink="/tasks/42" — and you must build and escape it yourself. The array form is a list of segments — [routerLink]="['/tasks', task.id]" — and the router joins and encodes each one.
The array form is safer, because a segment containing a slash, a space or a question mark is encoded rather than changing the meaning of the URL. Interpolating an unescaped value into a string is a real bug when ids are user-supplied strings.
It also composes: a leading '/' makes it absolute, a leading '..' makes it relative to the parent, and relative links need relativeTo on the routerLink or in the imperative navigate call.
Both forms take queryParams, fragment and state as separate inputs rather than being written into the string, which is the same encoding argument.
Land it Use the array form by default for anything containing a variable — the string form is fine only for genuinely static paths.
Q125 · Design. "Design the routing structure for an application with three user roles and twelve features."
Reveal answer
Strong answer I would start from bundles and permissions rather than from a URL diagram.
One lazy route per feature, each pointing at that feature's own routes file, so the folder boundary and the chunk boundary are the same line and deleting a feature is deleting a folder.
Role gating with canMatch, not canActivate, so a user without a role never downloads that feature's code. It also lets two roles resolve to different components at the same path, since a failed canMatch falls through.
A shell layout route wrapping the authenticated area, holding the navigation and providing anything the whole authenticated app needs. Login and error pages sit outside it so they do not render the shell.
Feature-scoped services in each feature route's providers, so feature state resets when the user leaves and does not accumulate in root.
URL shape by resource, not by role — /orders/42, not /admin/orders/42 — so a link works for anyone permitted to open it and the URL does not have to change when permissions do.
Then the standard pieces: a wildcard route last, a redirect from the empty path to each role's landing page, and server-side authorisation on every endpoint, because none of the above is security.
Land it Role in the URL path is the decision people regret: it duplicates every route per role and breaks every shared link the moment someone's permissions change.
- "How does the navigation menu know what to show?"
From the same permission source the guards use, not a second list. I would attach the required permission to each route's
dataand generate the menu from the route configuration, filtering by the current user's permissions.Keeping the menu and the guards in one place means a user cannot see a link that leads to a redirect, which is one of the most common polish failures in role-based applications.
These are opinion questions with right answers. The grading is whether you distinguish kinds of state and whether you escalate on evidence.
Q126. "How do you decide where a piece of state should live?"
Reveal answer
The real test Whether you separate server cache from client state before answering.
Strong answer By asking which of four kinds it is, because each has a natural home.
Server cache — a task list, a profile, search results. The server owns the truth and my copy is a stale snapshot, so it belongs in a resource with a freshness policy, not in a store I maintain by hand.
URL state — page, sort, filters, selected tab. The address bar owns it, and it arrives as component inputs.
Local UI state — is this panel open, which row is hovered. One component owns it and it should die with that component.
Shared client state — the signed-in user, feature flags, a cart, wizard progress. The application owns it, so a service with signals, scoped to root or to a route depending on when it should reset.
Most arguments about state management are really a failure to make this distinction, and putting server data in a global store is the expensive version of that mistake.
Land it The moment server data goes into a hand-maintained store, you have taken on cache invalidation — and you will end up writing a caching library inside your state library.
Q127. "When would you introduce NgRx, and what does it actually buy?"
Reveal answer
Strong answer It buys four specific things: an action log where every change is a named serialisable event; time-travel debugging over that log; a hard boundary between intent and state change, which scales across teams who do not read each other's code; and effects as a declared side-effect layer.
The costs are several files per feature, a second mental model for every joiner, and a strong pull toward putting server data in the store.
So my rule is: adopt it if the team would actually use the action log. If nobody would open the devtools timeline to debug, you are paying for a feature you do not consume.
I would reach for it in a large multi-team application with genuinely complex shared client state, or where an audit trail of user intent has real value. For most applications a service with signals is the honest answer, and saying so is not a lack of ambition.
Land it What is being graded here is whether you escalate on evidence, so naming the pressure that would change your mind matters more than which answer you give.
- "Where does SignalStore fit?"
Between a hand-written service and full NgRx. It gives structure — state, computed, methods, hooks, entity helpers, composable features — with signal ergonomics and no actions or reducers.
What it adds over a hand-written service is convention: every store in the codebase has the same shape, which matters when twenty people are writing them. What it does not add is the global action log, which is the thing you would escalate to full NgRx for.
Q128. "How do you keep a large Angular codebase's module boundaries from eroding?"
Reveal answer
Strong answer With enforcement, because conventions alone survive about a quarter.
The structure is by feature, not by technical type — a folder per feature with its own components, services, models and routes — plus a core/ for things there is one of and a shared/ for reusable presentational pieces with no feature knowledge.
The enforcement is lint rules on import paths: features may import from shared and core, shared may import from neither, and features may not import from each other. In a monorepo, Nx tags do this natively; otherwise an ESLint import-boundary rule does.
The test I apply is whether deleting a feature means deleting one folder. If that leaves dangling imports across the codebase, the boundary was decorative.
And I would keep shared/ narrow with an explicit rule: something belongs there only if two or more features use it and it knows nothing about any of them. A component taking a Task input is not shared.
Land it Unenforced boundaries are documentation, and documentation loses to deadlines every time.
Q129. "What is a facade, and do you use them?"
Reveal answer
Strong answer A facade is a service that sits between components and the state layer, exposing a small task-shaped API — loadOrders(), orders, isLoading — so components never touch the store's internals.
With NgRx it earns its keep, because it hides actions and selectors, and it means swapping the state library later touches one file per feature instead of every component.
With a signal service it is usually redundant. The service already exposes read-only signals and a small set of methods, so a facade in front of it is a second class forwarding calls, and every new feature means editing two files.
So my position is: facade when the underlying state layer has a verbose API you want to hide, and not otherwise. Adding one by default is ceremony.
Land it The signal store already is the facade, which is a large part of why signals reduced the amount of architecture people feel they need.
Q130 · Scenario. "Two features both need 'the current organisation'. Where does it go and who fetches it?"
Reveal answer
Strong answer This is ambient state, so it belongs in a root-provided service — but the fetching decision matters more than the location.
I would model it as a resource whose input is the organisation id, so it is a cache with loading and error states rather than a value someone must remember to load. Both features read the same signals and neither triggers a fetch.
Where the id comes from decides the rest. If it is part of the URL — /orgs/:orgId/... — it is URL state and should arrive through the route, which also makes the app multi-tab friendly and shareable.
If it is a session-level selection with no URL representation, it lives in the service and I would persist it so a refresh does not reset it — accepting that two tabs can then disagree unless they synchronise.
What I would avoid is each feature fetching it independently, which produces duplicate requests and two copies that can drift.
Land it Putting the organisation id in the URL solves several problems at once — deep links, multi-tab, and the "which org was I in" question after a refresh.
The last twenty of this block. Testing questions reveal seniority faster than most, because they expose whether you have maintained a suite or only written one.
Q131. "What is your testing strategy for an Angular application?"
Reveal answer
Strong answer Three layers with different jobs and very different costs.
Unit tests for services, stores, validators, guards and pure functions — no TestBed, constructed directly, running in milliseconds. This is where the business rules are, so this is where most of the tests go.
Component tests for the rendering contract: given this state, does the user see this. Loading, error, empty and populated for every data screen, plus the interactions that matter.
End-to-end tests for a small number of critical journeys — sign in, the main task, checkout. They are slow and flaky in proportion to how many you have, so I keep the count low and the value per test high.
What I do not do is chase a coverage number. Coverage measures which lines ran, not whether behaviour is correct, and optimising it produces tests that assert on implementation details and break on every refactor.
Land it The suite's job is to let people change the code confidently, so a test that breaks on a refactor without catching a defect is a liability rather than an asset.
Q132. "How do you test a signal-based service?"
Reveal answer
Strong answer Usually with new and nothing else, which is one of the underrated wins of the signal model.
A service holding signals and pure methods is an ordinary class. I construct it, call methods, and read signals synchronously — no TestBed, no fixtures, no change detection, no async.
If it injects dependencies I pass fakes to the constructor, or use TestBed.runInInjectionContext when it uses inject() in field initialisers.
The tests worth writing are the derivations — that a computed gives the right answer across the interesting cases — and the invariants, particularly that updates replace rather than mutate, since a later "optimisation" into a push would silently break change detection everywhere.
For effects, I would test the function they call rather than the effect itself, because effect scheduling drags in the framework's timing for no benefit.
Land it The immutability test is the one people skip and the one that pays: it converts a subtle rendering bug into a failing unit test.
Q133. "What changed when Angular moved from Karma to Vitest?"
Reveal answer
Strong answer Vitest became the default runner in Angular 21. The practical differences are speed and environment.
Karma launched a real browser and ran tests in it, which was accurate and slow — a suite that takes minutes under Karma often takes seconds under Vitest.
Vitest runs in Node with a simulated DOM, using the same build pipeline as the application, so there is no separate test bundling step and watch-mode reruns are near-instant.
The trade is fidelity: a simulated DOM is not a browser, so layout, real CSS behaviour and browser-specific APIs are approximations. Anything that genuinely depends on rendering belongs in a browser-based end-to-end test.
The migration is mostly mechanical — the assertion and mocking APIs differ from Jasmine — and Angular ships a migration tool for it.
Land it The speed change is not a convenience, it is a behaviour change: a suite that runs in five seconds gets run before every commit, and one that takes four minutes does not.
Q134. "How do you test a component that uses httpResource?"
Reveal answer
Strong answer With provideHttpClient() and provideHttpClientTesting() in the TestBed, then HttpTestingController exactly as for any HTTP code.
The sequence is: create the fixture, call detectChanges() so the resource's request is issued, use expectOne(url) to assert the right URL was requested — which catches a wrong endpoint or a missing encoding — and flush() the response.
Then await fixture.whenStable() and another detectChanges() before asserting on the DOM, because the resource settles asynchronously.
The three tests I would always write are the loading state before flushing, the populated state after, and the error state by flushing a 500 — the last is the branch nobody exercises manually and the one users hit on a bad network.
I would also test that changing an input signal re-issues the request with the new URL, since that dependency is the whole point of using a resource.
Land it Asserting the exact URL is worth more than it looks — a missing encodeURIComponent is invisible until someone searches for a term with an ampersand in it.
Q135 · Scenario. "Your test suite is flaky. How do you approach it?"
Reveal answer
Strong answer First I would treat flakiness as a defect rather than as noise, because a suite people do not trust is a suite people ignore, and then it protects nothing.
The usual causes in Angular, in order. Missing detectChanges or whenStable, so a test reads the DOM before the render — this passes or fails depending on machine speed. Shared state between tests, typically a root service or a module-level variable not reset. Real timers or real network leaking in. Test interdependence, where tests pass in order and fail when run in isolation or in parallel.
The diagnostic that works is running the suite with a randomised order and in isolation, which separates "this test is wrong" from "this test depends on that one".
And I would quarantine rather than retry: a test that needs three attempts is not passing, and automatic retries hide real intermittent bugs in the product.
Land it Retrying flaky tests trains the team to ignore failures, which is worse than deleting the test — at least a deleted test does not lie.
Q136. "What should a component test assert on, and what should it never touch?"
Reveal answer
Strong answer Assert on what the user can perceive: the text rendered, the number of rows, whether a control is disabled, what happens after a click, which output was emitted.
Never assert on private fields, internal method calls, or the presence of a particular CSS class used only for styling. Those are implementation, and a test coupled to implementation fails on every refactor without catching a single defect — which teaches the team that failures are noise.
For selecting elements, I prefer a dedicated test attribute over a CSS class or a tag path, because it survives markup changes and it documents which elements the test depends on.
The test I most want on any data component is the four states — loading, error, empty, populated — because those are four real screens and three of them are usually unexercised.
Land it The rule that keeps a suite valuable for years is that a test should fail when behaviour changes and not when structure changes.
Q137. "How do you test a guard, an interceptor and a resolver?"
Reveal answer
Strong answer All three are functions that need an injection context, so I run them inside TestBed.runInInjectionContext(() => guard(route, state)) with fakes provided.
For a guard I assert on the return value across the cases: true when permitted, and for the redirect case that the returned UrlTree points where I expect, including the returnUrl.
For an interceptor I use HttpTestingController with the interceptor registered, make a request, and assert on the outgoing headers — plus the failure paths, which for an auth interceptor means the 401-refresh-retry sequence and the stampede case.
For a resolver I assert on the resolved value and, more importantly, on what happens when the underlying request fails — an unhandled error there blocks navigation entirely, which is a much worse failure than a component's error state.
These are small functions with large blast radius, so they are among the highest-value tests in the codebase.
Land it The resolver's failure path is the one worth insisting on: a rejected resolver is a navigation that silently does nothing, and users report it as "the link is broken".
Q138. "What are component harnesses and are they worth it?"
Reveal answer
Strong answer A harness is an API for interacting with a component in a test without knowing its DOM — harness.setValue('x') rather than querying an input and dispatching an event.
Angular Material ships them for its components, and the CDK lets you write your own.
They are worth it for a shared component library, for two reasons. Consumers' tests no longer break when the library changes its internal markup, which is otherwise a constant source of churn. And the same harness works in unit tests and in end-to-end tests, so the interaction logic is written once.
For application components used in one place they are usually not worth the extra file — a test attribute and a query is enough.
Land it The value scales with how many tests depend on a component's internals, which is why libraries need them and one-off components do not.
Q139. "How do you test something involving timers or debouncing?"
Reveal answer
Strong answer With fake timers, so the test controls time rather than waiting for it. In Vitest that is vi.useFakeTimers() and vi.advanceTimersByTime(250).
The assertions worth making are the ones the debounce exists for: that nothing happened before the interval elapsed, and that rapid successive inputs produce exactly one call rather than several.
Angular's own fakeAsync with tick() does the same for code inside the Angular zone, and remains useful in zone-based applications. In a zoneless app, the runner's fake timers are the more direct tool.
What I would avoid is a real setTimeout in a test to "wait for" the debounce. It makes the suite slow, and it is flaky by construction because the margin that works on a developer machine fails on a loaded CI runner.
Land it Any test containing a real sleep is a future flaky test — the only question is which CI run finds it.
Q140. "What would you put in CI for an Angular project?"
Reveal answer
Strong answer Six gates, ordered so the fast ones fail first.
Type checking and lint, which are seconds and catch the most. Unit and component tests with --watch=false. A production build, because a build that only succeeds in development is a deploy waiting to fail.
Bundle budgets, so a dependency that adds 300 KB fails the build rather than being discovered a month later — this is the one people leave out and regret.
End-to-end tests for the critical journeys, on the production build, since that is what users get.
And a dependency audit, plus a check that lockfiles are committed and consistent.
Beyond gates, I would add a Lighthouse or Web Vitals run on a representative page and track it over time. Performance regressions are otherwise invisible until someone complains.
Land it Bundle budgets are the highest-value underused gate, because bundle growth is completely invisible in code review.
Q141. "How do you keep an Angular application up to date across major versions?"
Reveal answer
Strong answer One major at a time with ng update, which runs the official migration schematics rather than only bumping versions. Skipping versions means running migrations out of order and is where upgrades go wrong.
Angular's six-month cadence makes this manageable if you do it routinely and painful if you do not — an application three majors behind is a project, and one behind is an afternoon.
The order that works: update Angular first, then Angular-dependent libraries, checking each one supports the target version before starting. A library that has not been updated is the usual blocker, and finding that out first saves a wasted day.
Then run the suite, run the production build, and check the deprecation warnings, because they are the next version's breaking changes.
The optional migrations are worth running deliberately — control flow, standalone, inject, signal inputs — since each removes a class of legacy the next migration would otherwise have to handle.
Land it The strategy that keeps this cheap is treating the upgrade as routine maintenance on a schedule rather than a project someone proposes.
Q142 · Scenario. "You inherit a five-year-old Angular application. What do you do in the first week?"
Reveal answer
Strong answer I would spend the week understanding and measuring, not changing.
Establish the baseline. Which Angular version, does it build, does the test suite pass, how long does CI take, what is the bundle size, and what do the real user metrics say.
Read the shape. app.config.ts or the root module tells me what is switched on. The routes file tells me the feature map and what is lazy. The folder structure tells me whether boundaries exist.
Find the risk. Dependencies that are unmaintained or block an upgrade, any bypassSecurityTrust calls, secrets in the repository, and how much of the code is in files over a thousand lines.
Ask the team what they are afraid to touch. That answer is worth more than any static analysis, because it names the parts with no tests and no owner.
Then I would propose a sequence rather than a rewrite: upgrade to a supported version first, because everything else is easier from there, then add tests around the areas people fear, then modernise incrementally.
Land it The instinct being tested is whether you propose a rewrite in week one — and the answer that lands is a migration path with measurable checkpoints.
Q143. "How would you migrate a large application from modules to standalone?"
Reveal answer
Strong answer With the official schematic, in its three stages, one at a time with a release between them.
The first pass converts components, directives and pipes to standalone and adds their imports arrays. The second removes now-unnecessary NgModules. The third switches bootstrapping to bootstrapApplication.
What makes it safe is that the two worlds interoperate: a standalone component can import an old module to use its exports, and an NgModule can list a standalone component in its imports. So there is no big-bang step.
The parts that need judgment are the module-level providers. A service in a lazy module's providers had a scope, and moving it to providedIn: 'root' silently changes its lifetime — that is the duplicate-instance bug in reverse, and it is the main thing to review by hand.
I would also expect the schematic to leave standalone: true written explicitly, which is redundant on Angular 19 and later and can be cleaned up in a separate mechanical pass.
Land it The mechanical part is a schematic; the part that needs a human is provider scope, because that is the one thing the tool cannot infer intent about.
Q144. "What lint rules or conventions would you insist on for an Angular team?"
Reveal answer
Strong answer Six, chosen because each prevents a class of bug rather than enforcing taste.
Strict TypeScript and strictTemplates on, non-negotiable, because turning them off to unblock something disables checking everywhere.
No bare .subscribe() in components — push people to toSignal, the async pipe, or an explicit takeUntilDestroyed.
No function calls in template bindings beyond event handlers, which prevents the per-render cost and the identity churn.
Import boundary rules between features, shared and core.
Bundle budgets in the build, treated as a lint rule for size.
An accessibility rule set — the Angular ESLint template rules catch missing labels, click handlers on non-interactive elements and bad ARIA, which is a large share of the automatable issues.
Beyond rules, one convention: a providers array on a component is a deliberate statement about instance scope and gets a comment saying why.
Land it Every rule here maps to a specific bug I have seen ship, which is the standard I would apply before adding a seventh.
Q145. "How do you review someone's Angular pull request? What do you look for first?"
Reveal answer
Strong answer In this order, because it goes from expensive-to-fix-later to cheap.
State ownership. Who writes this value, and can anyone else? A new providers array, a public writable signal, or a component mutating an input are the things that will cost days later.
Cleanup. Every subscription, listener and third-party widget — is it torn down, and is the teardown next to the setup?
The four states. If it fetches, does the template handle loading, error, empty and populated, and is the error branch distinguishable from empty?
Template cost. Method calls in bindings, object literals in inputs, missing or unstable track.
Then naming, structure and tests.
What I try not to do is lead with style. Style comments are easy to write and crowd out the two or three observations that actually matter, and the author learns to skim reviews.
Land it The first two categories are where the expensive bugs live, and a review that only reaches naming has not really been a review.
Q146. "How do you monitor an Angular application in production?"
Reveal answer
Strong answer Three streams, because they answer different questions.
Errors, via a replaced ErrorHandler reporting to a service with the route, the user id, the release version and a correlation id — plus unhandled promise rejections, which the default handler misses. Source maps uploaded per release, or every stack trace is minified noise.
Real user performance, not synthetic: Core Web Vitals collected from actual sessions, segmented by device and connection. A laboratory Lighthouse score on a fast machine hides the experience of the median user.
Product analytics for whether journeys complete, since a page that renders perfectly and where nobody finishes checkout is still broken.
I would also tie the release version into all three, so a regression can be attributed to a deploy, and set alerts on error rate and on the vitals rather than only watching dashboards.
Land it Without source maps and a release identifier, production error reporting produces volume rather than information.
Q147. "What is your approach to internationalisation?"
Reveal answer
Strong answer Angular's built-in i18n uses i18n attributes in templates and produces one build per locale, so each user downloads only their language and there is no runtime translation cost.
The trade is that switching language means loading a different build, usually at a different URL — which is good for search engines and awkward for an in-app language switcher.
Runtime libraries such as Transloco keep one build and swap translations at runtime, which suits applications where users switch language often.
Either way, the parts people underestimate are the same: pluralisation rules differ by language and cannot be done with string concatenation; date, number and currency formatting must use the locale-aware pipes rather than manual formatting; text length varies by around thirty percent between languages, so layouts must not assume English width; and right-to-left languages need logical CSS properties rather than left and right.
And translator context matters — a key with no description produces a translation that is grammatically correct and wrong in place.
Land it Choosing between build-time and runtime is really a question about how often a single user changes language, and everything else follows from it.
Q148 · Scenario. "A bug only reproduces for one customer, in production. How do you investigate?"
Reveal answer
Strong answer I would work from what differs, because "only one customer" is itself the strongest clue.
First, gather facts rather than guesses: browser and version, screen size, the exact URL, the time, and whether it is every user at that customer or one person. Error reports with a correlation id let me find the failing request in the backend logs.
Then enumerate what could be customer-specific: their data — an unusual character, a very long name, an empty collection, a record count above a threshold; their configuration — feature flags, permissions, locale, timezone; their environment — a corporate proxy, an extension, a locked-down browser, a content security policy.
Session replay, where available, is the fastest path from "cannot reproduce" to a video of it happening.
If I still cannot reproduce, I would add targeted logging behind a flag for that customer rather than guessing at a fix, because a speculative fix that does not work costs another release cycle to discover.
Land it "Only one customer" nearly always means their data or their configuration, and asking for an export of the failing record is usually faster than any amount of code reading.
Q149. "What would make you choose not to use Angular for a new project?"
Reveal answer
Strong answer Four situations, and being able to name them is part of being trusted to choose it elsewhere.
A mostly static site — marketing, documentation, a blog. The shipped JavaScript would outweigh the content, and a static site generator produces a faster page with less work.
A small embeddable widget, where footprint is the whole requirement and Angular's opinions about routing and forms are irrelevant.
A team already fluent in something else with no reason to switch. Team familiarity beats framework merits for almost any timeline that matters.
A project whose hiring pool is React, in a market where that is what people know. Framework choice is a hiring decision as much as a technical one.
Where I would choose it: a long-lived application with many screens and several engineers, especially in a domain full of forms, and especially where consistency across a large team is worth more than flexibility.
Land it Being able to argue against your primary tool is what makes an argument for it credible.
Q150 · Design. "Design the testing strategy for a team of twelve shipping daily."
Reveal answer
Strong answer The constraint that shapes everything is the feedback loop: twelve people shipping daily means CI must be fast enough to run on every push and trustworthy enough that a red build stops the line.
Fast gates on every push, targeting under five minutes: type check, lint, unit and component tests, production build, bundle budgets. Parallelised, and with test selection by affected project if it is a monorepo.
A small end-to-end suite on the main branch — the five or six journeys whose failure would be an incident, run against a production build. Not one per feature, because the maintenance cost scales worse than the value.
Post-deploy verification: a smoke test against the real environment, plus alerting on error rate and Core Web Vitals, so problems that only appear in production are found by the system rather than by a customer.
Zero tolerance for flakiness. A flaky test is quarantined the same day and either fixed or deleted within the week, because the alternative is a team that ignores failures.
And a convention rather than a coverage target: every pull request that changes behaviour changes a test. That is reviewable, whereas a percentage is gameable.
Land it With daily releases, the ability to deploy a fix quickly is part of the testing strategy — a fast, safe rollback is worth more than the marginal end-to-end test that would have caught it.
- "How do you stop the end-to-end suite growing into a two-hour job?"
By giving it an explicit budget and an owner. Each test must justify itself against a stated journey, and adding one is a decision rather than a habit.
The pressure to add them usually comes from missing coverage at a cheaper layer — an end-to-end test written because a component test would have been awkward. Fixing the awkwardness is cheaper than paying for that test on every run forever.
Feature flags help too: shipping behind a flag reduces the need for pre-merge end-to-end coverage of unfinished work.
12 · DrillPerformance, SSR & Architecture Design — Q151–Q200
The last fifty are the ones that decide a senior title rather than confirm a mid-level one.
They are graded differently. Nobody expects a single right answer to "design the frontend for a marketplace". They expect requirements stated before a design, trade-offs named out loud, and at least one thing you would refuse to do.
Answer these the way you would in the room: say what you would clarify, then the design, then what you would give up.
Each of these is a symptom. The graded part is the order in which you rule things out, and whether you measure before you change anything.
Q151. "A page is slow. Walk me through your diagnosis from nothing."
Reveal answer
The real test Whether you separate the three budgets before touching anything.
Strong answer First I would find out which kind of slow, because the three have different causes and different fixes.
Slow to arrive — the page is blank for seconds on first visit and fine afterwards. That is the download budget: bundle size, too many requests, no compression, no caching.
Slow to become usable — content appears but clicks do nothing. That is startup: too much work at bootstrap, an app initialiser, hydration of the whole page.
Slow while using it — typing lags, scrolling stutters. That is the interaction budget: change detection, list rendering, expensive template work.
I would identify which by looking at real user metrics if they exist, or by recording a load and an interaction in Chrome's performance panel on a throttled profile with a production build.
Only then would I open the Angular profiler, because it answers "which component and how often" and is useless if the problem turns out to be a 2 MB image or a missing gzip header.
Land it The most common mistake is optimising change detection when the actual problem is that the page ships 1.8 MB of JavaScript on a mobile connection.
Q152. "What are Core Web Vitals and how does an Angular app affect each one?"
Reveal answer
Strong answer Three metrics, and each maps to different Angular decisions.
Largest Contentful Paint — when the biggest visible element renders. Dominated by bundle size and by whether the content needs JavaScript to appear at all, so lazy routes, @defer, SSR or prerendering, and NgOptimizedImage with priority on the hero image are the levers.
Interaction to Next Paint — how quickly the page responds to input, across the session. This is where change detection, list rendering and long tasks show up, and where hydration matters because a fully rendered page that has not hydrated does not respond at all.
Cumulative Layout Shift — how much content jumps around. Caused by images without dimensions, content injected above existing content, fonts swapping, and @defer placeholders that are a different size from what replaces them.
Layout shift is the one Angular developers most often cause and least often measure, because it does not show up on a fast connection where everything arrives at once.
Land it A @placeholder that is not the same size as the deferred content converts a bundle-size win into a layout-shift regression, which is why the minimum-duration options exist.
Q153 · Scenario. "Your initial bundle is 1.8 MB. Get it under 500 KB."
Reveal answer
Strong answer I would look before cutting: ng build --stats-json and a treemap, because the biggest rectangle is usually a surprise and the biggest win is usually one dependency.
Then in order of typical yield:
Lazy-load every feature route. On an application with a dozen features this alone often halves the initial bundle, and it is mechanical.
Fix the dependency that dominates. Namespace imports of utility libraries, a date library including every locale, an icon package imported through a barrel, a charting library imported eagerly for one dashboard.
@defer the heavy things inside pages — editors, charts, maps — which are usually below the fold anyway.
Check the shared module. A "shared" module that acquired a feature dependency drags that feature into the initial chunk for everyone.
Then set a budget just above the achieved number so it cannot regress, and verify with the network tab on a throttled profile rather than trusting the build output alone.
Land it Almost every 1.8 MB bundle I have seen was two or three specific decisions rather than general bloat, which is why measuring first saves days.
- "The largest item is a library you cannot remove. Now what?"
Check whether it ships an ES-module build, because a CommonJS-only package cannot be tree-shaken at all — Angular's build even warns about this. Sometimes a maintained fork or a modern alternative exists.
If it must stay whole, isolate it: put every use behind a lazy route or a
@deferblock so only the users of that feature pay for it.And check for duplication — two versions of the same library in the tree is common and doubles the cost for nothing.
Q154. "How do you make a long list fast, and what are the options in order?"
Reveal answer
Strong answer Cheapest first, and I would stop as soon as it is fast enough.
Fix track. Without a stable identity every render rebuilds every row. This is free to fix and is often the whole problem.
Make the row cheaper. Fewer elements, fewer bindings, formatting in a computed or a pure pipe rather than a method, no nested component per cell.
Render fewer rows. Pagination is the simplest and usually the best product answer, because a user cannot meaningfully scan five hundred rows anyway.
Virtual scrolling when the list genuinely must be continuous — it renders only the visible window plus a buffer, at the cost of known row heights, broken find-in-page, and accessibility work.
Move the work to the server when the data is large: filter, sort and page there, so the browser holds one page at a time regardless of the dataset.
I would measure between steps, because the first two often make the rest unnecessary.
Land it Virtual scrolling is where people start and where they should finish — it is the most complex option and frequently unnecessary once the row is cheap.
Q155. "What is hydration, what can go wrong, and how do you detect it?"
Reveal answer
Strong answer Hydration is the client-side application adopting the server-rendered DOM rather than rebuilding it: it walks the existing nodes, matches them to the components that would have created them, and attaches event listeners.
What goes wrong is a mismatch — the client would have rendered something different from what the server produced. Angular reports it as a hydration error in development and falls back to destroying and re-creating that part, which produces a visible flicker and loses the benefit.
Three causes dominate. Invalid HTML nesting that the browser silently corrects, such as a <div> inside a <p> — the server's string and the browser's parsed DOM then differ.
Values that differ between server and client: Date.now(), random numbers, anything reading window to decide what to render.
Direct DOM manipulation before hydration completes, which moves nodes out from under the matcher.
Detection is the console in development, plus checking the network waterfall for a double fetch that indicates transfer state is not working.
Land it Invalid nesting is the one that surprises people, because the page looks correct in both places and only the matcher notices the difference.
Q156. "SSR, prerendering, or client-only — how do you choose?"
Reveal answer
Strong answer By asking two questions: does the content depend on the user, and does anyone other than a logged-in user need to see it.
Prerendering — content that is the same for everyone. Rendered at build time to static HTML, served from a CDN with no server to run. Best first paint, lowest cost, right for marketing pages, documentation and public catalogues.
SSR — public content that is personalised or too dynamic to build ahead, or where the catalogue is too large to prerender. Same first paint, but you now run and scale a Node server and accept a class of server-only bugs.
Client-only — anything behind a login. No crawler sees it, users load it once and keep the tab open, and the operational cost buys almost nothing.
A single application can mix all three: prerender the marketing routes, server-render the public catalogue, and leave the authenticated application client-rendered.
Land it Turning SSR on for an internal tool is the common mistake — it adds a server to operate and a class of bugs in exchange for a benefit nobody in that audience experiences.
Q157 · Scenario. "After enabling SSR, your server's response time is 900 ms at the 95th percentile. Investigate."
Reveal answer
Strong answer Server rendering time is dominated by two things: waiting for data, and waiting for the application to become stable.
I would check the second first, because it is the pathological case. If something never completes — an interval, a WebSocket, a long-lived subscription started at bootstrap — the render waits until a timeout. The symptom is a long tail rather than a uniformly slow response, which matches a 95th percentile complaint.
Then the data. Every request the components make happens server-side and serially unless deliberately parallelised, so a page with four dependent fetches pays all four latencies. Aggregating or parallelising them is the main lever, and the server is usually closer to the API than the browser is, so this should be fast.
Then the mechanics: is there any caching at all? Many pages are identical for large groups of users and can be cached at the edge with a short lifetime, which removes most renders entirely.
And is the render itself expensive — a very large component tree rendered to string on every request, where incremental hydration or splitting the page would reduce the work.
Land it A never-stable application is the signature of a 95th-percentile problem specifically, because it only bites when the timeout is reached rather than on every request.
Q158. "What is incremental hydration and when is it worth the complexity?"
Reveal answer
Strong answer With full hydration, the browser must download and execute the JavaScript for the entire page before anything is interactive — so a rendered page can sit there looking ready and ignoring clicks.
Incremental hydration, enabled with withIncrementalHydration() and used as @defer (hydrate on viewport), keeps a block as inert server-rendered HTML until its trigger fires. The content is visible and indexable immediately; its code arrives only when needed.
It is worth it on content-heavy pages where much of the page is below the fold — a product page with reviews and recommendations, an article with a comment section, a long dashboard.
It is not worth it on a page that is one interactive form, where everything is needed at once and the added structure buys nothing.
The care it requires is that a block which has not hydrated does not respond to interaction, so anything the user might click immediately must hydrate on interaction rather than on viewport.
Land it The metric it moves is Interaction to Next Paint rather than first paint, which is precisely the gap that makes server-rendered pages feel broken.
Q159. "How do you handle third-party scripts without wrecking performance?"
Reveal answer
Strong answer Third-party scripts are usually the largest performance problem on a commercial page and the one engineers have least control over, so I would start by counting them and measuring their share of main-thread time.
Then, in order: remove what nobody uses — there is always at least one tag from a campaign that ended two years ago.
Load the rest late and asynchronously, after the page is interactive, never blocking rendering.
Load on interaction where possible — a chat widget loaded when the user clicks the chat button rather than on every page view is often a several-hundred-kilobyte saving for a feature one percent use.
Move what can be moved server-side, such as analytics via a server-side tag manager, which removes the client cost entirely.
And I would set a policy: a third party must have an owner, a purpose and a review date, or the list only grows.
Land it Engineers optimise their own bundle by kilobytes while a marketing tag adds hundreds — measuring third parties separately is what makes that visible to the people who add them.
Q160. "What does the Angular service worker give you, and what does it cost?"
Reveal answer
Strong answer @angular/pwa adds a service worker that caches the application shell and assets, so repeat visits load from cache and the app works offline for anything cached. It also provides SwUpdate for detecting and activating new versions.
The benefits are near-instant repeat loads and a graceful story when the network is poor.
The costs are real. Caching bugs are hard to debug because the user is running code you did not just deploy, and a bad service worker can pin users to a broken version — the reason a reliable unregister-and-recover path matters.
Update behaviour needs a decision: activating immediately can swap the code under a user mid-task, while waiting means they run an old version until they reload. I would prompt them and let them choose.
And the service worker registration is deliberately delayed until the app is stable, so an application that never stabilises never registers it.
Land it A service worker is a deployment mechanism as much as a caching one, and treating it as a checkbox is how teams end up unable to ship a fix.
Q161 · Scenario. "Users on 3G report the app is unusable. Everything is fine internally. What do you do?"
Reveal answer
Strong answer The first problem is that the team cannot see it, so I would make it visible before proposing anything.
That means collecting real user metrics segmented by connection and device, so the difference between the office and the field is a number rather than a claim. It also means testing on a throttled profile with CPU throttling as part of normal work, because a fast laptop hides everything.
Then the likely causes, in order: total download size, because a 1.5 MB bundle is fifteen seconds on a slow connection; the number of round trips, since latency dominates over bandwidth on mobile; images not sized or formatted for small screens; and no useful content until JavaScript has run.
The fixes follow: aggressive route splitting and deferring, an image strategy with modern formats and correct sizes, prerendering or SSR so something meaningful arrives in the first response, and reducing the number of requests needed for a first useful screen.
And a product decision worth raising: a lightweight path for constrained clients, even if it offers less, is better than a rich experience nobody can load.
Land it The durable fix is making the slow case measurable and visible in CI, because otherwise every subsequent feature reintroduces the problem.
Q162. "How would you profile and fix a memory leak in production?"
Reveal answer
Strong answer Reproduce it locally with a scripted version of the user's pattern, because production heap analysis is impractical.
The method is a heap snapshot comparison: snapshot, perform the suspect cycle ten times — usually navigating in and out of a screen — force garbage collection, snapshot again, and compare. A component class whose instance count grows by ten is the answer.
From there the retainer path in DevTools shows what is holding it, which is nearly always one of four things: a subscription to a stream that never completes, a listener added by hand, a third-party widget never destroyed, or a long-lived service holding a reference.
The fixes are takeUntilDestroyed(), DestroyRef.onDestroy for non-observable cleanup, and calling the third party's own destroy method.
To catch it earlier next time I would add the navigate-ten-times check to a periodic performance test, since leaks are otherwise found by users after six hours.
Land it The retainer path is the part that turns a suspicion into a line number, and it is the step people skip in favour of guessing.
Q163. "What is the performance cost of Angular itself, honestly?"
Reveal answer
Strong answer The framework runtime for a modern standalone, zoneless application is in the region of 45 to 60 KB compressed — smaller than the reputation, because standalone components, dropping Zone.js and better tree-shaking removed a lot.
That is a fixed cost paid once and cached. In practice it is rarely what makes an application slow; application code, dependencies, images and third-party scripts dominate.
The runtime cost is change detection, which with signals and OnPush is proportional to what actually changed rather than to the size of the page.
Where Angular genuinely costs more than a lighter alternative is the floor: a small widget will always be smaller without a framework, and for a mostly static page the framework is pure overhead.
Where it costs less is at scale, because the structure that feels heavy at one screen is what keeps forty screens consistent.
Land it Quoting a rough number rather than defending the framework is what makes the answer credible — and the number is small enough that it is rarely the real problem.
Q164. "How do you prevent performance regressions rather than fixing them?"
Reveal answer
Strong answer By making regressions fail something, because anything that only appears on a dashboard gets ignored.
Bundle budgets in the build, set just above current size, so a dependency that adds 300 KB fails CI rather than being discovered later. This is the single highest-value control.
A Lighthouse or Web Vitals run on key pages in CI, with thresholds — noisy, so I would use it as a trend with generous limits rather than a hard gate on every commit.
Real user monitoring with alerts, segmented by device and connection, because laboratory numbers miss the population that matters.
A dependency review step: adding a package is a decision with a size attached, and the pull request should say what it costs.
And culturally, testing on a throttled profile as normal practice, so the slow case is something the team experiences rather than reads about.
Land it Performance work that is not defended by automation is undone within two quarters, which is why the budget in the build matters more than any single optimisation.
Q165. "When would you take part of a page out of Angular entirely?"
Reveal answer
Strong answer When the update rate is far above the rate at which a user can perceive change, and the framework's per-update cost is therefore pure overhead.
The genuine cases are narrow: a canvas visualisation at sixty frames per second, a live order book, a drag interaction where the moving element must follow the pointer exactly, a large data grid with its own virtualisation.
The technique is to detach that component from change detection or keep the work in a requestAnimationFrame loop started in afterNextRender, writing to the DOM or canvas directly, and to set signals only at meaningful boundaries — the drag ended, the selection changed.
The cost is that the normal mental model no longer applies to that component, so it needs a comment explaining why and a boundary that keeps the exception contained.
I would do it only after profiling proves the remaining cost is Angular's rather than the browser's layout and paint, because it usually is not.
Land it Escaping the framework is a legitimate technique and a bad default — one documented component is fine, five is a codebase nobody can reason about.
The questions a lead is asked. Each wants requirements first, a design second, and an explicit list of what you would not do.
Q166 · Design. "Design the frontend architecture for an application with 40 screens and 15 engineers."
Reveal answer
Strong answer At that size the design problem is coordination, not code, so I would optimise for independent work and enforced boundaries.
Structure by feature, one folder per feature owning its components, services, models and routes, each behind its own lazy route so the folder boundary and the chunk boundary coincide.
Enforced import rules: features may import from shared and core, shared from neither, features not from each other. Lint rules, not documentation, because conventions erode.
A narrow shared, admitting something only if two features use it and it knows about neither.
A design system as its own library with its own versioning, so fifteen people are not each styling a button.
State by kind: server data in resources, URL state in the URL, feature state in route-scoped services, ambient state in a few root services. No global store unless the action log would genuinely be used.
Conventions that remove decisions: a standard component shape, a standard store shape, a standard error and loading treatment — so a reviewer is checking behaviour rather than arguing about structure.
What I would avoid at this size is micro-frontends. Fifteen engineers in one repository is well within what a monorepo handles, and the runtime and operational cost would buy nothing.
Land it The single test for whether the boundaries are real is whether deleting a feature means deleting one folder.
- "How do teams share components without coupling?"
Through the design system library, which is a published dependency with a version rather than a folder people reach into. It contains presentational components with no domain knowledge — a button knows nothing about orders.
When two features need the same domain-aware component, that is a signal the domain concept belongs in its own library both depend on, rather than one feature importing from the other.
- "How do you keep 40 lazy chunks from becoming 40 duplicated copies of the same dependencies?"
The build extracts shared code into common chunks automatically, so a library used by three lazy routes is emitted once rather than three times.
What breaks that is inconsistent versions — two features depending on different versions of the same package genuinely does duplicate it. A single lockfile and a shared dependency policy in a monorepo prevents it, and the bundle analyser makes it visible when it happens.
Q167 · Design. "When are micro-frontends the right answer, and how would you implement them in Angular?"
Reveal answer
Strong answer They solve an organisational problem, not a technical one: independent teams that must deploy on independent schedules without coordinating a release.
So the honest test is whether teams are actually blocked on each other's releases today. If a monorepo with clear boundaries would do, that is cheaper in every dimension.
The implementation in Angular is Module Federation, where a shell application loads remote modules at runtime and Angular itself is shared as a singleton rather than duplicated per remote.
The costs are substantial and worth stating. Version alignment: every remote must agree on the Angular major version, so upgrades become a cross-team negotiation — often the very coupling micro-frontends were meant to remove. Shared state across remotes has to go through an explicit contract. Bundle size grows because sharing is imperfect. Debugging spans applications. And end-to-end testing needs the whole composition running.
I would consider them for a genuinely large organisation with separately deployable products, and push back for a single product with several teams.
Land it The framework-version negotiation is the trap: teams adopt micro-frontends for independence and discover they are more coupled at upgrade time than they were in one repository.
Q168 · Design. "Design a component library for use by five product teams."
Reveal answer
Strong answer The hard parts are theming, versioning and accessibility, not the components.
Layer it. Design tokens as CSS custom properties at the bottom, then unstyled behavioural primitives, then styled components. Consumers who need something unusual can drop a layer instead of forking.
Theme with custom properties, never by letting consumers write selectors into the components. Custom properties cross view encapsulation and shadow DOM, and they are a published contract rather than a reach-in that breaks on every internal change.
Build on the CDK for overlays, focus management, keyboard navigation and live announcements. Re-implementing those is where a library quietly becomes inaccessible.
Ship component harnesses, so consumers' tests do not break when internal markup changes — this is the difference between a library people upgrade and one they pin.
Version it properly with semantic versioning, a changelog, deprecation warnings before removals, and migration schematics for breaking changes. Five teams cannot all migrate on the same day.
And a documented policy for what does not belong: anything domain-aware, and anything used by one team.
Land it A library without harnesses and migrations gets pinned to an old version by the first team that gets burned, and then it has failed.
Q169 · Design. "Design a real-time collaborative editing screen."
Reveal answer
Strong answer I would first establish what collaborative means here, because the answer differs enormously between "two people rarely" and "twenty people simultaneously in the same paragraph".
For coarse-grained collaboration — different people editing different records or fields — presence indicators plus field-level locking or last-write-wins with a conflict warning is usually enough, and is a fraction of the work.
For genuine concurrent editing of the same text, I would not hand-roll it. That needs conflict-free replicated data types or operational transformation, and a mature library such as Yjs is the right answer; writing your own is a research project.
The Angular side is then: a service owning the connection and the document, exposing signals for content, presence and connection state; local edits applied immediately and sent asynchronously; and remote changes merged without disturbing the local cursor, which is the detail that makes or breaks it.
Beyond the merge: throttle outgoing updates rather than sending per keystroke, handle reconnection with a resync, and show connection state honestly so a user knows when their edits are not being saved.
And the editing surface itself should not be a plain contenteditable — that is a decade of browser inconsistencies best left to an editor library.
Land it The senior move is scoping: most requests for "collaborative editing" are satisfied by presence and locking, and saying so saves a quarter.
Q170 · Design. "Design the frontend for a data-heavy admin application: 30 tables, complex filters, exports."
Reveal answer
Strong answer With thirty similar screens, the design decision is to build the table once and configure it thirty times.
One generic table component taking a column configuration, and templates for custom cells through ng-template with context. Thirty hand-written tables is thirty places to fix any bug.
Server-side everything — filtering, sorting, pagination. The browser holds one page. Anything else fails at the first large customer.
All table state in the URL: page, size, sort, filters. It makes every view shareable and bookmarkable, survives refresh, and makes the back button behave — which in an admin tool is a daily-use feature, not a nicety.
A shared filter model, so filters serialise to query parameters consistently across all thirty screens and can be saved as named views.
Exports server-side, asynchronous, with a notification when ready. Generating a CSV in the browser dies at a few hundred thousand rows and blocks the tab while it tries.
Then the details that make it usable: keep previous rows visible while loading rather than flashing empty, debounce filter input, use cursor pagination if the data shifts under the user, and make bulk actions state clearly how many records they will affect.
Land it The two decisions worth defending are one table component and URL-as-state; both are painful to retrofit after twenty screens exist.
- "How do you keep the generic table from becoming an unmaintainable configuration language?"
By capping what configuration can express and using templates for the rest. Column definitions cover the common cases declaratively; anything unusual is a cell template the consuming screen writes.
The failure mode is a configuration object that grows into a programming language with worse tooling — every new requirement becomes a new flag. When a flag would only ever be used once, that is a template, not a feature.
Q171 · Design. "Design an approach for feature flags in an Angular application."
Reveal answer
Strong answer Flags arrive at startup, ideally from the same call that establishes the session, and live in a root service exposing them as signals so anything reading one re-renders when it changes.
Consumption is at three levels. A canMatch guard for a whole feature, which also prevents the chunk from being downloaded. An @if in a template for a section. And a signal read in a service for behavioural differences.
The parts people get wrong are the lifecycle ones. Flags must expire — every flag needs an owner and a removal date, or you end up with two hundred and no idea which combinations are tested. The number of combinations grows exponentially, so tests should cover the intended states, not the cartesian product.
And a flag controlling something sensitive must be enforced server-side. Hiding a button does not prevent the request.
For gradual rollout I would let the server decide which cohort a user is in and send a resolved boolean, rather than shipping the targeting rules to the browser where they can be read and edited.
Land it A flag without a removal date is permanent complexity, and the cost is not the flag — it is every future engineer reasoning about a branch nobody remembers.
Q172 · Design. "Design the error and empty-state strategy for an application."
Reveal answer
Strong answer I would make it a system rather than a per-screen decision, because inconsistency here is what makes an application feel unfinished.
Four states, always, on every data surface: loading, error, empty, populated. Empty and error must look different, because "you have no orders" and "we could not load your orders" mean opposite things to the reader.
Errors say what to do next, not what went wrong internally. A retry button where retrying might help, a contact route where it will not, and a reference id the user can quote — never a status code or a stack trace.
Empty states distinguish first-use from filtered-to-nothing. A new user with no data needs an explanation and a call to action; a user whose filter matched nothing needs a way to clear the filter.
Scope the failure. One failed panel should not blank the page; each region reports its own state so the rest stays usable.
Implementation-wise, shared components for each state plus a convention that every resource-backed template has four branches, so it is reviewable at a glance.
Land it Rendering a failed request as an empty list is the most common production defect in frontends, and it costs exactly one extra branch to avoid.
Q173 · Design. "How would you introduce Angular into a company that has none?"
Reveal answer
Strong answer Not by announcing a standard. I would pick one real project of moderate importance and build it properly, so the argument is a working system rather than a proposal.
Before that, I would be honest about whether it is the right choice: the hiring market locally, what the team already knows, and whether the applications are the kind Angular suits — many screens, forms-heavy, long-lived.
Alongside the first project: a starter template encoding the conventions, so the second project does not re-litigate structure; a small set of written decisions about state, folder structure and testing; and pairing rather than documentation for the first few weeks, because the framework's learning curve is front-loaded.
Then I would set an explicit review point — after the first delivery, does the team want to continue — rather than treating adoption as irreversible.
What I would avoid is rewriting an existing working application to prove the point. That spends a year producing what already exists, and it is how framework migrations get a bad name.
Land it The credible version of this answer includes the conditions under which you would conclude it was the wrong call.
Q174 · Design. "Design the frontend for a checkout flow."
Reveal answer
Strong answer Checkout is the screen where every general principle becomes a specific requirement, because failure has a monetary cost.
Never lose the cart. Server-side, so it survives device changes, with a local copy for speed. Not localStorage alone.
Idempotent submission. The client generates an idempotency key per attempt; a retry or a double click cannot charge twice. This is a contract with the backend and it is non-negotiable — see E6 for the server side.
exhaustMap on the pay action, so a second click while the first is in flight is ignored rather than queued or racing.
No optimism about payment. Optimistic updates are right for a like and wrong here; the user waits for a real answer, and the pending state must be unambiguous.
Explicit handling of the unknown outcome. If the request times out, the client does not know whether the payment succeeded. The interface must say so and offer a safe way to check, rather than showing failure and inviting a second attempt.
No card data in the application. A hosted field or payment element from the provider, so the page is out of scope for card handling entirely.
Then the ordinary care: steps as routes so back works, autosaved address details, validation before the payment step rather than after, and a clear final review.
Land it The idempotency key plus the timeout-with-unknown-outcome case are what separate a checkout that has been through an incident from one that has not.
- "The user closes the tab mid-payment. What happens?"
The server continues; the outcome does not depend on the browser staying open. When the user returns, the application should look up the order by its idempotency key or reference and show the real state.
That means the pending order must be recorded before the payment call, not after, or there is nothing to look up. It is a backend design point that the frontend requirement forces.
Q175 · Design. "Design an Angular application that must work for 10,000 concurrent users of a live event dashboard."
Reveal answer
Strong answer Ten thousand concurrent users is a backend and delivery problem far more than a rendering one, so I would start there.
Do not open ten thousand WebSockets if you can avoid it. If everyone sees the same data, publish snapshots to a CDN on a short interval and poll — it is cacheable, scales trivially, and degrades gracefully. Reserve sockets for genuinely per-user data.
Coalesce updates on the client. Whatever the transport, buffer incoming data and apply at most once per animation frame, so a burst does not turn into a render per message.
Bound the DOM. Only what is visible exists; virtualise long lists and lazy-load panels below the fold.
Serve the shell statically. Prerender or SSR behind a CDN so the initial load does not depend on an origin that is also handling the event traffic.
Degrade deliberately. Under load the page should slow its update rate rather than fail — a dashboard updating every five seconds is far better than one that has stopped responding.
And I would load-test the real path, because the failure at ten thousand users is usually connection limits or a cache-miss stampede, not component rendering.
Land it The answer that lands is choosing cacheable polling over per-user sockets where the data is shared, because it converts a scaling problem into a CDN configuration.
Questions with no single right answer, where what is graded is whether you name the trade-off and commit to a position you can defend.
Q176. "What is the biggest mistake you have made in an Angular codebase?"
Reveal answer
The real test Whether you can describe a real failure with a mechanism and a lesson, rather than a disguised humblebrag.
Strong answer Have a genuine one ready with four parts: what was built, what went wrong, how it was found, and what changed afterwards.
A good shape, if you need a pattern: putting all server data in a global store, because it seemed like the disciplined choice. The consequence was owning cache invalidation — refetch on navigation, on focus, on a timer — and a growing pile of code that was a worse caching library than the ones that exist.
How it was found: two screens showing different totals for the same data, repeatedly, with no single bug to fix.
What changed: separating server cache from client state, moving reads to resources with an explicit freshness policy, and keeping the store for genuinely client-owned state.
The lesson worth stating is that the mistake was not a wrong library, it was failing to notice that "state" meant two different things with different owners.
Land it A specific failure with a mechanism is far more credible than a general one, and "I learned to distinguish server cache from client state" is a lesson that transfers.
Q177. "How do you decide between fixing something properly and shipping the workaround?"
Reveal answer
Strong answer By asking what the workaround costs if it becomes permanent, because most of them do.
A workaround that is local, visible and documented is often the right call under time pressure — a comment naming the real cause and a ticket is a legitimate engineering artefact.
A workaround that spreads is not. Suppressing an ExpressionChanged error with setTimeout, switching a component to always-check to mask a mutation bug, or adding detectChanges() until a screen updates — those hide a defect that will be reproduced elsewhere by the next person, because the underlying pattern is still there.
So my test is whether the workaround makes the real problem harder to find later. If it does, I would rather ship the bug visibly and fix it next, than ship a fix that removes the evidence.
And I would be explicit with whoever is asking about the trade, rather than absorbing it silently — that is a decision with a cost, and it belongs to the person who owns the deadline.
Land it The distinction that matters is between a workaround that is contained and one that removes the evidence of the real cause.
Q178. "A junior wants to add a state management library. How do you respond?"
Reveal answer
Strong answer I would ask what problem they hit, because the answer determines everything and it is usually specific.
If it is "I cannot get this value to two components", the answer is a service with signals and it takes ten minutes.
If it is "I cannot tell what changed this value", that is a real pain and the fix is a private writable signal with a read-only public view and named methods — most of what a store was going to buy them.
If it is "I want devtools and an action log", that is a legitimate reason to adopt one, and I would want to know whether the team would actually use it.
If it is "this is what I have used before", I would say so plainly and explain the escalation ladder rather than dismissing them.
The framing I would use is that every layer of architecture is a cost paid by everyone who joins afterwards, so it should be bought with a specific pain rather than a preference.
Land it Asking what pain prompted it turns a tooling argument into a design conversation, and usually the pain has a cheaper fix.
Q179. "What Angular feature do you think is over-used?"
Reveal answer
Strong answer Effects. They are the tool people reach for when they have not yet seen the derivation.
The pattern is an effect that reads one signal and sets another, which is a computed written the hard way: it runs later, it can loop, it hides the relationship from anyone reading the code, and Angular warns about it.
A close second is component-level providers. It looks like configuration and it is actually a statement that this state is per instance, which is almost never what the author meant.
Third is the async pipe used several times on the same observable, producing duplicate requests that nobody notices because each one succeeds.
What connects all three is that the wrong choice still works. Nothing fails at build time, the screen looks right, and the cost appears later as a bug that seems unrelated to the line that caused it.
Land it If an effect's last statement is a set, it wanted to be a computed — that one rule removes most of the misuse.
Q180. "How do you keep up with Angular's release pace?"
Reveal answer
Strong answer By treating upgrades as routine maintenance rather than projects — one major every six months, run with ng update, scheduled rather than proposed.
For knowing what changed, the primary sources are the release blog posts and the roadmap on the official site, which state what is stable, what is developer preview and what is deprecated. Deprecation warnings in a build are the most reliable early signal, since they are the next version's breaking changes.
What I try not to do is adopt everything immediately. A feature in developer preview is an invitation to experiment on something low-risk, not to build a critical path on it.
And the schematics matter more than the reading: ng update runs the official migrations, and the optional ones — control flow, standalone, inject, signal inputs — are worth running deliberately, because each removes legacy the next migration would otherwise carry.
Land it Being one version behind is an afternoon and three versions behind is a project, which is the entire argument for putting it on a schedule.
Q181 · Scenario. "Your team disagrees about whether to adopt Signal Forms now. Argue both sides."
Reveal answer
Strong answer For adopting now: they are stable as of Angular 22, they remove the duplication between a form object and a model, form state becomes signals like everything else so there is no observable bridge, and starting now means new forms are not written in something that will be legacy.
Against: the ecosystem is younger — fewer answers, fewer library integrations, fewer people on the team who have hit the edge cases. Reactive forms are what every existing form uses, what every interview asks about, and what every article describes. And a mixed codebase means two mental models for the same job.
My position: new features in Signal Forms, existing forms left alone, and no migration for its own sake. compatForm() exists precisely so a large application can move one form at a time when it is already being changed.
The decision I would push back on is a big-bang migration of working forms, because it spends a large amount of effort to produce something that already works.
Land it "New code in the new thing, old code left alone, converted when touched" is the migration policy that works for almost every framework change.
Q182. "What would you standardise across a team, and what would you deliberately leave to individuals?"
Reveal answer
Strong answer I would standardise the things where inconsistency has a cost beyond the file: folder and boundary structure, the shape of a store, how loading and error states are presented, the testing approach, and anything with a security or accessibility implication.
I would leave to individuals the things that are genuinely taste and are contained: how a function is broken up, naming within a file, whether a small helper is inlined.
The dividing line is whether a reader in six months is affected. A store with a surprising shape costs everyone; a variable named result instead of response costs nobody.
And I would enforce the standards mechanically where possible — lint rules, schematics, a starter template — because a standard that lives in a document is re-litigated in every review and lost within two quarters.
Land it Standardising too much is as expensive as too little: it turns reviews into style arguments and crowds out the two comments that mattered.
Q183 · Scenario. "You are asked to cut a feature's delivery time in half. What do you give up?"
Reveal answer
Strong answer I would name what I am giving up explicitly rather than absorbing it, because an unstated compromise becomes an expectation.
What I would cut: scope, first and hardest — half the feature shipped well beats all of it shipped badly. Then polish that can be added later: animations, empty-state illustrations, keyboard shortcuts. Then generalisation — build it for this case and refactor when the second case exists.
What I would not cut: the error and loading states, because an application that silently fails generates more work than it saved. Accessibility basics, because they are cheap during and expensive after. Security checks. And tests on the business rules, which are the fastest tests to write and the ones that let the next change be fast.
I would also say what the compromise costs and when it comes due — "this is not built for the second product type, adding one is a week" — so the decision belongs to whoever is asking.
Land it Cutting scope is almost always better than cutting quality, because scope can be added later and quality is repaid with interest.
Q184. "How do you approach accessibility as a team practice rather than a checklist?"
Reveal answer
Strong answer By moving it earlier, because retrofitting is where the cost is.
In the design system, so the components everyone uses are already correct — focus management, keyboard behaviour, contrast, ARIA wiring. That covers most of the surface without every engineer becoming an expert.
In lint and CI, with the Angular ESLint accessibility rules and an axe check in component tests. Automation catches perhaps a third of real issues, but it catches them on every commit for free.
In the definition of done: a keyboard pass on every new screen, which takes two minutes and finds most of what automation misses.
In design, because contrast and touch-target sizes are decided before any code exists, and fixing them afterwards means changing the design.
And periodically with a screen reader on the critical journeys, because it reveals a category of problem — meaningless announcements, unlabelled controls, an order that makes no sense — that nothing else finds.
Land it The highest-value single habit is using native elements: every hand-built substitute has to re-implement keyboard behaviour the browser already ships.
Q185. "What does 'senior' mean in a frontend role, in your view?"
Reveal answer
Strong answer Three things beyond writing the code well.
Owning the consequences. Not just does the feature work, but what it costs to load, how it fails, whether it can be debugged in production, and what it does to the next person's change.
Deciding rather than preferring. Naming the trade-off, choosing, and being able to state the condition under which the choice would be wrong. "We used signals in services and never needed a store, and here is what would change my mind" is a senior answer; "we always use NgRx" is not.
Making other people faster. Conventions that remove decisions, reviews that catch the expensive things rather than the stylistic ones, and building the thing that lets five people work without coordinating.
And a fourth that is easy to leave out: knowing what not to build. Most of the value in a senior role is scoping — noticing that the request for collaborative editing is satisfied by presence indicators, or that the table needs pagination rather than virtualisation.
Land it The shortest version is that a senior engineer is judged on the decisions, not the code — and on the ones that are still good in a year.
Q186. "Explain change detection to a backend engineer in two minutes."
Reveal answer
Strong answer "Your screen is built from a tree of components, and each one has a small list of expressions that fill holes in its HTML.
Change detection is a pass over that tree. For each component it re-runs those expressions, compares each result with what it stored last time, and updates the page only where the value differs. There is no observation of your fields and no diffing of a virtual page — it is re-evaluate and compare.
The only question worth asking is which components get skipped. Historically Angular could not tell what had changed, so a library patched every timer and event handler to say 'something happened', and the framework re-checked everything.
Now values that can change are held in signals, which record who read them. So when one changes, exactly the components that read it are marked, and the rest of the tree is skipped without being evaluated at all.
The practical consequence is the one rule: if a template reads it, it must be a signal — otherwise nothing knows it changed."
Land it Being able to explain it without jargon is a genuine signal, because it means the model is yours rather than remembered vocabulary.
Q187 · Scenario. "A stakeholder says the app 'feels slow' but every metric is green. What do you do?"
Reveal answer
Strong answer I would take it seriously rather than defending the numbers, because "feels slow" usually means the metrics are measuring the wrong thing.
First I would watch them use it, on their machine and their connection, and ask them to point at the moment. That is usually enough — it is often one specific action, not the application.
The common causes of a green dashboard and a slow feeling: metrics averaged rather than at the 95th percentile, so a slow tail is invisible; measurement on developer hardware; the measured page not being the one they use; and feedback rather than speed — an action that takes 400 ms with no indication feels slower than one taking 800 ms with a response.
That last one is the most common. A button that does nothing visible for half a second reads as broken, and the fix is an immediate state change rather than a faster request.
Then I would add a metric that captures what they experience — Interaction to Next Paint on that specific action — so the conversation next time is about a number both sides trust.
Land it Perceived performance is a real engineering property: immediate feedback, keeping stale content visible and avoiding layout jumps often beat making anything faster.
Q188. "How would you design an Angular app to be testable from the start?"
Reveal answer
Strong answer Testability is mostly a consequence of separation, so I would design for the seams rather than for the tests.
Business logic in plain classes. Stores and rules that hold signals and pure functions and know nothing about HTTP or the DOM can be constructed with new and asserted synchronously.
Transport separate from state. An API client that only knows URLs and shapes, so rules can be tested without stubbing a network.
Presentational components taking inputs and emitting outputs, with container components doing the injecting. The presentational half is then testable by setting inputs, with no providers at all.
Everything through dependency injection, so there is always a substitution point — no direct imports of singletons, no reading globals in constructors.
Stable test hooks in markup, so tests select by intent rather than by structure.
Each of those is a design improvement independently, which is the point: code that is hard to test is usually hard to change for the same reasons.
Land it Difficulty writing a test is diagnostic — it names the coupling, and the fix for the test is usually the fix for the design.
Q189. "What is the relationship between Angular and TypeScript, and does that constrain you?"
Reveal answer
Strong answer Angular is written in TypeScript and assumes it. Decorators carry configuration the compiler reads, templates are type-checked against component classes under strictTemplates, and dependency injection historically used parameter type metadata to know what to provide.
That last point is why inject() is an improvement beyond ergonomics: it does not depend on emitted type metadata at all, which is one reason Angular can move with the language rather than being pinned to a decorator implementation.
The constraint is real but narrow: you cannot sensibly write an Angular application in plain JavaScript, and the build is tied to a supported TypeScript range, so upgrading one usually means upgrading the other.
In exchange you get template type checking, which catches a whole category of error that is a runtime surprise in most other frameworks, and refactoring that actually works across templates.
Land it Template type checking is the underrated part: renaming a property and having every template that used it fail to build is not something most frameworks offer.
Q190 · Design. "Design the frontend observability for an application you own."
Reveal answer
Strong answer I would aim to answer three questions from data rather than from reports: is it broken, is it slow, and does it work.
Is it broken — a replaced ErrorHandler reporting with route, user, release and correlation id, plus unhandled rejections which the default misses. Source maps uploaded per release, or every trace is unreadable. Alert on error rate per release so a bad deploy is visible in minutes.
Is it slow — Core Web Vitals from real sessions, segmented by device and connection, reported at the 95th percentile rather than averaged. Plus timing on the specific interactions that matter for this product.
Does it work — funnel completion for the main journeys, because a page that renders perfectly and where nobody finishes checkout is broken in the way that counts.
Tying them together: the same release identifier and correlation id across all three, and across to backend traces, so a frontend error can be followed to the request that caused it.
And a deliberate decision about what not to collect, because analytics that captures user content is a privacy problem you have created for yourself.
Land it The correlation id joining frontend errors to backend traces is what turns two dashboards into one investigation.
Q191. "What is your view on Angular Material versus building your own components?"
Reveal answer
Strong answer It depends almost entirely on how strong the design requirements are.
Use Material when the product does not need a distinctive look — internal tools, admin panels, anything where shipping quickly and being accessible matters more than being unique. You get keyboard behaviour, focus management, ARIA and theming that would take a team a year.
Use the CDK without Material when you have a design system of your own. That is the sweet spot: you own every pixel and inherit overlays, focus trapping, live announcements and virtual scrolling.
Build from scratch only when you have both a strong design language and the capacity to own accessibility properly. Most teams that choose this underestimate the second part, and the result is a beautiful component set that a keyboard user cannot operate.
The mistake I would warn against is taking Material and fighting its styles. Overriding a component library's internals produces something that breaks on every upgrade and is harder to maintain than either alternative.
Land it The CDK-without-Material option is the one people miss, and it is usually the right answer for a team with its own designers.
Q192 · Scenario. "Half your codebase is legacy patterns and half is modern. How do you converge?"
Reveal answer
Strong answer With a policy rather than a project, because a convergence project competes with product work and loses.
New code is written in the new style, always, with lint rules enforcing the parts that can be enforced.
Touched code is converted opportunistically — if you are changing a component anyway, migrate it. That concentrates the effort where the code is actually alive, and leaves untouched files alone, which is correct because untouched code is not costing anything.
Mechanical migrations are run in bulk, since the schematics for control flow, standalone, inject and signal inputs are reliable and reviewable as one commit per feature.
The genuinely hard parts get scheduled — provider scoping during a standalone migration, or removing Zone.js dependence — because those need judgment and cannot be a background activity.
And I would track it visibly, so progress is a number rather than a feeling. What I would not do is stop feature work to converge, or start a rewrite.
Land it Converting only what you touch is the policy that finishes, because it spends effort exactly where the code is being read and changed anyway.
Q193. "What questions would you ask before designing any frontend?"
Reveal answer
Strong answer Six, and asking them is itself the thing being graded in a design round.
Who uses it, on what? Desktop office workers and rural mobile users produce completely different designs.
Is it public or authenticated? That decides rendering strategy — search visibility versus no crawler at all.
How much data, and where does filtering happen? A hundred rows and a hundred thousand are different products.
How fresh must data be? Seconds, minutes or on-demand decides polling versus sockets versus nothing.
What is the team and the timeline? Three engineers for a quarter and fifteen for two years justify different amounts of structure.
What must never break? Every product has one or two flows where failure is expensive, and they deserve disproportionate care.
The answers usually eliminate most of the design space before any architecture is discussed.
Land it Producing a design without asking any of these is the most common failure in a design round, and it is a scoping failure rather than a knowledge one.
Q194. "How would you explain the value of signals to a manager who does not write code?"
Reveal answer
Strong answer "The screen has to stay in step with the data. The old approach was that whenever anything at all happened — a timer, a click, a network response — the framework re-checked the entire page, because it had no way to know what had changed.
Signals let a value announce its own changes, so only the parts of the screen that use that value are updated. Everything else is skipped.
Three consequences that matter to you. The application does less work, so it is more responsive on the cheap phones a lot of our users have. We ship less code, because we removed the library that did the guessing. And a whole category of bug goes away — the ones where the screen shows stale data and nobody can reproduce it."
I would then attach a number if I have one: a specific screen's interaction time before and after, or the reduction in stale-data bug reports.
Land it The persuasive part is the third consequence, because a class of bug disappearing is something a manager has felt the cost of.
Q195 · Scenario. "Your app must support a browser two years out of date for one large customer. What now?"
Reveal answer
Strong answer First I would establish the actual cost rather than accepting or refusing on principle: which browser and version, what share of users, and specifically which features are missing.
Then the mechanics. The build's browser support list drives what the compiler outputs, so widening it means more transpilation and larger, slower bundles for everyone — that is the cost to state clearly.
A differential approach avoids the tax on modern users: serve a modern bundle to modern browsers and a compatibility bundle to the rest, at the cost of two builds and two test matrices.
I would also check whether the blockers are framework or platform. Angular's own baseline is a hard limit; missing platform features such as container queries or newer CSS can often be handled with a fallback layout rather than a polyfill.
And I would ask the commercial question, because "one large customer" usually means someone can ask them to upgrade — supporting an old browser is a recurring cost on every future feature, not a one-off.
Land it The framing that helps is that browser support is a recurring tax on every future change, so it deserves a commercial decision rather than a silent engineering one.
Q196. "What is the most useful thing you have learned about Angular that is not in the documentation?"
Reveal answer
Strong answer That almost every hard problem reduces to one of three questions, and identifying which one saves most of the debugging time.
When does it re-render? Stale screens, ExpressionChanged errors, a page burning CPU while idle.
Who owns this instance? Two panels disagreeing, state that will not reset, NG0201, memory that never frees.
What is still subscribed? Leaks, duplicate requests, handlers firing after navigation.
The documentation explains each mechanism well, but it does not tell you that these three categories cover nearly everything, or that the first diagnostic step is deciding which one you are in.
The practical version: when a screen is wrong, ask whether it was not checked or checked-and-unchanged. When something behaves twice, log identity. When something happens after it should have stopped, look for a subscription. Those three checks resolve most incidents before a debugger is opened.
Land it Having a triage order rather than a search strategy is most of what experience buys in a framework this size.
Q197. "How do you onboard someone onto a large Angular codebase?"
Reveal answer
Strong answer With a route through the code rather than a tour of it.
Day one is running it and shipping something tiny — a copy change, a fixed label — so the whole loop from checkout to deploy is exercised before any architecture is discussed.
Then reading in a specific order: app.config.ts for what is switched on, the routes file for the feature map and what is lazy, then one feature end to end from route to component to store to API client.
Then a real task in that feature, paired, because the questions that matter only appear when someone is trying to change something.
What I would document rather than explain repeatedly: the conventions and the reasons for them, and — most valuably — a short list of the surprising parts, the places where this codebase does something unusual and why. That list saves more time than any diagram.
What I would avoid is a week of architecture presentations before they have touched anything, because none of it sticks without a problem to attach it to.
Land it The list of surprising parts is the highest-value document in any large codebase and the one almost nobody writes.
Q198. "Angular or React for a new greenfield product — argue it properly."
Reveal answer
Strong answer I would refuse to answer it as a technical question first, because the deciding factors are usually not technical.
Hiring. Which do people in this market know? A framework you cannot staff is a bad choice however good it is.
Existing skills. A team fluent in one will ship faster in it for at least two quarters.
The shape of the product. Many screens, forms-heavy, long-lived, several teams — Angular's included routing, forms and consistency earn their keep. Unusual interfaces, a need to pick best-of-breed libraries, or a heavy server-rendered content site — React with a meta-framework has the stronger ecosystem.
Ecosystem needs. If the product depends on a specific library that exists in one ecosystem, that often settles it.
Technically they have converged: both do fine-grained reactivity, both do server rendering and streaming, both have mature tooling. The difference is that Angular decides more for you and React lets you decide more, and which is better depends entirely on how many people are deciding.
Land it The answer that fails is a list of framework features; the answer that lands names hiring, existing skills and product shape before anything technical.
Q199 · Design. "Design a frontend platform: what would you build once so 20 teams do not each build it?"
Reveal answer
Strong answer I would build the things that are identical everywhere and expensive to get right, and refuse to build the things that are product-specific.
A design system — tokens, primitives, components, with accessibility and theming solved once and harnesses so consumers' tests survive upgrades.
An application starter — a schematic generating a project with the conventions, lint rules, CI pipeline, error handling, monitoring and authentication already wired. This is the highest-leverage item, because it makes the right structure the default rather than a document.
Shared cross-cutting libraries: authentication, HTTP setup with interceptors, error reporting, feature flags, analytics, internationalisation. Each is a week per team otherwise, and twenty subtly different implementations later.
A shared build and CI configuration, so budgets, gates and upgrade paths are consistent and can be changed centrally.
Upgrade support — migration schematics and a team that runs the Angular upgrade across repositories, because twenty teams each doing it independently is the largest hidden cost of a platform.
What I would not build: domain components, opinionated state management, or an abstraction over Angular itself. The last is the classic platform failure — a wrapper that becomes a worse framework nobody can hire for.
Land it A platform team's output is other teams' velocity, so anything that slows a team down to satisfy the platform is a defect in the platform.
Q200 · Design. "You are the first frontend hire at a company building a complex product. What do you do in the first ninety days?"
Reveal answer
The real test Whether you sequence for compounding value rather than listing everything you know.
Strong answer I would sequence it so each phase makes the next cheaper.
Weeks 1–2: understand before deciding. Who the users are, on what devices and connections; what the product must do in a year; what the backend looks like and whether the API contracts are stable; what the team knows.
Weeks 3–4: choose and justify. Framework, structure, state approach, testing, CI. Written down with reasons, because the reasons are what let the next person change it deliberately. And chosen for the team that will exist in a year, not for me.
Weeks 5–8: build one feature properly, end to end. Not a prototype — a real feature with routing, forms, data, error and loading states, tests, monitoring and a deployment. That becomes the reference implementation and settles more arguments than any document.
Weeks 9–12: make it repeatable. Extract the conventions into a starter and a small component set, set up lint rules and bundle budgets, wire error reporting and real user monitoring, and write the short list of decisions and surprises.
Throughout, ship something visible early. Ninety days of platform work with no product to show for it is how a first frontend hire loses the room, however good the platform is.
Land it The reference implementation is the highest-leverage artefact — it is a convention people can copy, which is worth more than a document people will not read.
- "What if the backend is not ready?"
I would agree the API contract first and build against a mock derived from it — a schema both sides generate from, so the mock cannot drift from the real thing silently.
That unblocks frontend work immediately and, more usefully, surfaces contract disagreements in week two rather than week ten. The risk to manage is the mock diverging, so I would run at least one path against the real API as soon as any endpoint exists.
- "What would you deliberately not do in the first ninety days?"
No micro-frontends, no custom state management library, no abstraction layer over Angular, and no design system built before there are enough screens to know what it should contain.
All four are decisions that feel like foresight and are actually guesses. They are cheap to add once the shape of the product is known, and expensive to remove once everything depends on them.
13 · RecapWhat You Can Do Now
- You can describe a change detection pass exactly — the generated update function, the binding slots, the
Object.iscomparison — and explain why a template method call is expensive in two separate ways - You can list every trigger that schedules a render in a zoneless application, and use that list to diagnose a stale screen without a debugger
- You can explain the signal graph as push-then-pull, prove it is glitch-free with the diamond, and say why dependencies are dynamic rather than declared
- You can choose correctly among
signal,computed,effect,linkedSignaland the resource APIs, and say what each one is wrong for - You can describe both injector trees, the full resolution order, the four modifiers, and the exact windows in which
inject()is legal - You can diagnose "two instances where I expected one" in thirty seconds, and explain how provider location decides both instance count and lifetime
- You can choose among the four flattening operators from the concurrency requirement, place
catchErrorcorrectly, and name every stream that never completes - You can separate the four kinds of state, defend a position on NgRx by naming what it buys, and describe the escalation ladder with the pressure that moves you up it
- You can diagnose a slow page by budget — download, startup, interaction — and name the tool that answers each question
- You can explain hydration, its three failure modes, and when incremental hydration is worth the structure
- You can answer two hundred senior questions out loud, including the follow-ups, and say what you would refuse to build in each design question
There are no dumb questions
- I have used Angular for years and half of this is new. Is that normal?
- Yes, and it is the situation this chapter was written for. Angular changed more between 2023 and 2026 than in the six years before it — standalone components, signals, zoneless, built-in control flow, resources and Signal Forms all arrived in that window. Years of experience with the previous model is genuinely valuable; it is just aimed at a framework that has moved.
- Do I need to know RxJS deeply for a senior Angular role in 2026?
- Deeply enough for the four flattening operators, the error contract, cold versus hot, and cleanup — which is roughly this chapter's section 05. That is what interviews ask and what production code needs. The hundred operators you will not use are not the point; the concurrency decision is.
- Should I learn NgRx before interviewing?
- Learn what it buys — an action log, time travel, an intent boundary, a declared effects layer — well enough to say when you would and would not adopt it. That answer is stronger than syntax knowledge. If a specific employer's job description names it, learn the API too, because they will ask.
- How much of this comes up in an actual interview?
- Sections 02 to 05 are the reliable core: change detection, signals, dependency injection and RxJS come up in nearly every senior Angular round. Performance and SSR appear when the product is public-facing. The design questions appear at staff level and increasingly at senior. Sections 06 to 08 are what you are expected to have opinions about rather than recite.
- The design questions have no single answer. How am I graded?
- On four things: whether you ask what the requirements are before designing, whether you name trade-offs instead of presenting a design as obviously correct, whether you can say what you would not build, and whether your answer survives one follow-up. A confident wrong answer scores worse than an uncertain one that reasons out loud.
- Is it worth learning React as well?
- Yes, and not for employability alone. Learning the second one teaches you which parts of the first were the framework and which were the problem — you stop attributing to Angular things that are simply true of rendering data on a screen. Chapter E16 compares them directly and covers the architecture and design craft both share.
Close the page and write down, from memory: every trigger that schedules a change detection pass in a zoneless application; the four flattening operators with the canonical use of each; and the full injector resolution order including which tree is searched first. Then reach back to Chapter E9: a container reports the host's memory because /proc is not namespaced, so the JVM sizes its heap wrongly. Explain how that is the same class of bug as an OnPush component reading a mutated input — in both cases the observer is asking the wrong source about a value that has a different real owner.