Angular Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does Zone.js let Angular know when to run change detection?
Correct answer: It patches async browser APIs and tells Angular when a task finishes
Zone.js doesn't know *what* changed, only that some async work completed, so Angular checks the tree from the root (skipping OnPush subtrees that are not dirty). That is simple but can cause many unnecessary checks.
2. Why would you call
NgZone.runOutsideAngular()in a zone-based app?this.zone.runOutsideAngular(() => { window.addEventListener("mousemove", this.onMove); });Correct answer: So frequent events don't trigger change detection on each tick
Thousands of
mousemoveorrequestAnimationFramecallbacks would each trigger app-wide change detection (zone pollution). Re-enter withzone.run()only when the UI really needs an update.3. How do you enable zoneless change detection?
Correct answer: Add
provideZonelessChangeDetection()and dropzone.jsRecent Angular versions create new projects zoneless by default. Removing Zone.js reduces bundle size, makes stack traces cleaner and avoids unnecessary checks.
4. In a zoneless app, which of these does NOT schedule change detection?
Correct answer: A
setTimeoutcallback that writes to a plain fieldWithout Zone.js Angular relies on explicit notifications: signal updates,
markForCheck()(also used byasync),ComponentRef.setInput, template/host listeners and attaching dirty views. A plain field change in a timer is invisible.5. Which component style is already compatible with zoneless change detection?
Correct answer: OnPush components whose state lives in signals or flows through
async/markForCheckIf a component works correctly with OnPush, it is very likely zoneless-ready. APIs like
NgZone.onStable/onMicrotaskEmptydon't emit without Zone.js and should be replaced withafterNextRenderor signals.6. How does the default change detection traverse the component tree?
Correct answer: Top-down from the root, in a single pass
Unidirectional data flow is why changing parent state from a child during a check triggers
ExpressionChangedAfterItHasBeenCheckedErrorin development.7. What does "glitch-free" mean for Angular signals?
Correct answer: Consumers never see a mix of old and new values
Signals use a push/pull model: a change marks dependents as dirty, and values are recomputed lazily when read. A
computeddepending onaandbnever sees a newawith a staleb.8. What is wrong with this effect?
total = signal(0); constructor() { effect(() => this.total.set(this.price() * this.qty())); }Correct answer: Derived state should be
computed(), not synced by an effecttotal = computed(() => this.price() * this.qty())is synchronous, lazy and always consistent. UselinkedSignalif it must also be writable; reserve effects for side effects outside the signal graph (DOM, storage, logging).9. When would you pass a custom
equalfunction to a signal?user = signal<User>(initial, { equal: (a, b) => a.id === b.id && a.version === b.version });Correct answer: To skip notifying when the new object means the same
By default signals use
Object.is, so every new object triggers updates. A custom equality avoids recomputation and re-rendering when a refetch returns the same data.10. What does
httpResource(the resource API) provide?userId = input.required<string>(); user = httpResource<User>(() => `/api/users/${this.userId()}`); // template: @if (user.isLoading()) { ... } {{ user.value()?.name }}Correct answer: Signal-based data that refetches when the request signals change
Resources bring async data into the signal graph. When
userIdchanges, the previous request is aborted and a new one starts.reload()refetches manually.11. How do you clean up inside an
effectbefore it re-runs or is destroyed?effect((onCleanup) => { const id = setInterval(() => this.poll(this.url()), 5000); onCleanup(() => clearInterval(id)); });Correct answer: Register it with the
onCleanupcallback the effect getsThe cleanup runs before the next execution (when
urlchanges) and when the effect is destroyed with its injection context, preventing duplicated intervals.12. When is RxJS still a better fit than signals?
Correct answer: For event streams: debouncing, cancellation and retries
Signals model *state* (always have a current value); Observables model *events* and async flows. Many apps combine them with
toSignal/toObservableat the boundaries.13. When might you use
ChangeDetectorRef.detach()?Correct answer: For a very busy widget that you refresh manually at a set rate
A detached view is skipped by change detection until it is
reattach()ed or checked manually. It is a sharp tool: forgetting to update leaves the UI stale.14. An OnPush parent has an OnPush child that reads a signal in its template. The signal changes. What is refreshed?
Correct answer: Only the child view that reads the signal
Since Angular 17, signal changes mark the consuming view for refresh and its ancestors only for traversal. This "local" change detection is far cheaper than
markForCheck, which re-checks every ancestor.15. Why are getters or methods in templates a common performance problem?
@for (p of filteredProducts(); track p.id) { <li>{{ p.name }}</li> } filteredProducts() { return this.products.filter((p) => p.visible); }Correct answer: They run on every check, and each new array re-evaluates the list
Turn derived data into a
computed()signal or a pure pipe: it is recalculated only when the inputs change. Profile with Angular DevTools to find components that check too often.16. In which order does Angular resolve
inject(Token)in a component?Correct answer: Element injectors up the tree, then environment injectors
The nearest provider wins, which is how a component can override a root service for its subtree. If nothing is found,
NullInjectorthrows unless the injection is optional.17. What is
runInInjectionContextfor?runInInjectionContext(this.injector, () => { const data = toSignal(inject(Api).load(id)); });Correct answer: Calling
inject()and similar APIs outside the constructorInject
Injectorduring construction, then use it later in a method or callback. Many APIs (toSignal,effect,takeUntilDestroyed) alternatively accept aninjectoroption.18. A recursive tree node component needs its parent node. Which injection option fits?
export class TreeNode { parent = inject(TreeNode, { skipSelf: true, optional: true }); }Correct answer:
skipSelfto start at the parent, plusoptionalfor the rootWithout
skipSelf, the node would find itself.selflimits lookup to the current element injector;hoststops at the host component's boundary.19. How do you load configuration before the app renders?
providers: [ provideAppInitializer(() => inject(ConfigService).load()), ]Correct answer:
provideAppInitializerwith a function that returns a PromiseBootstrap waits for initializers to finish. Keep them fast and handle errors: a failed initializer blocks the whole application from starting.
20. What is the difference between
providersandviewProvidersin a component?Correct answer:
viewProvidersare hidden from content projected into the componentUse
viewProvidersto keep an internal service private, so components passed in through<ng-content>by the parent can't accidentally inject it.21. Why use an abstract class as a DI token?
export abstract class Storage { abstract get(key: string): string | null; } providers: [{ provide: Storage, useClass: LocalStorageService }]Correct answer: It is a contract that exists at runtime, so it can be swapped
Interfaces are erased at compile time and can't be tokens. An abstract class gives both a type and a runtime token, which is the Angular way to depend on abstractions.
22. What does hydration do in an Angular SSR app?
Correct answer: Reuses the server-rendered DOM and attaches listeners to it
Enabled with
provideClientHydration(). Reusing the DOM avoids flicker and improves LCP and CLS. It requires the server and client to produce the same DOM structure.23. What commonly breaks hydration with a mismatch error?
Correct answer: Direct DOM manipulation or different server and client markup
Hydration expects the DOM it finds to match the component tree. Avoid manual DOM changes, fix invalid HTML (like
<div>inside<p>), or mark a component withngSkipHydrationas a last resort.24. What problem does
withEventReplay()solve?Correct answer: Clicks made before hydration ends are replayed afterwards
Server-rendered pages look interactive before the JS is ready. Event replay captures early events and dispatches them once the handlers are attached.
25. What does incremental hydration add?
@defer (hydrate on viewport) { <app-reviews /> }Correct answer: Server HTML stays dehydrated until the block's trigger fires
Enabled with
withIncrementalHydration(). Users see the full HTML immediately, but the JS for below-the-fold parts is deferred, improving time to interactive.26. Why doesn't the client repeat the API calls made during SSR?
Correct answer:
HttpClientembeds GET responses in the page and reuses themThe HTTP transfer cache is part of
provideClientHydration()and is configurable withwithHttpTransferCacheOptions. Without it the client would refetch and could flash different data.27. How do you safely use browser-only APIs (
window,localStorage) in an SSR app?Correct answer: Call them in
afterNextRenderor behindisPlatformBrowserafterNextRenderandafterEveryRendernever run on the server. For values needed in both environments, use an injectable abstraction with a server and a browser implementation.28. What does the
priorityattribute do withNgOptimizedImage?<img ngSrc="hero.jpg" width="1200" height="600" priority />Correct answer: Marks the LCP image, so it loads eagerly at high priority
ngSrcimages are lazy by default, which is wrong for the hero image. The directive also requireswidth/height(orfill) to prevent layout shifts and can generatesrcsetvia a loader.29. How do you preload lazy routes after the initial page has loaded?
Correct answer:
withPreloading(PreloadAllModules)inprovideRouterPreloading keeps the initial bundle small and still makes later navigation instant. A custom strategy can preload only routes flagged in
data, or only on fast connections.30. What are budgets in
angular.json?Correct answer: Size limits for bundles that warn or fail the build
Budgets with
maximumWarning/maximumErrorcatch accidental bundle growth in CI, e.g. when someone imports a heavy library into the initial chunk.31. Why might a component inside
@deferstill end up in the main bundle?Correct answer: It is also referenced outside the defer block in that file
Dependencies of a defer block must be standalone and used only inside it. Any eager reference forces the compiler to load them eagerly.
32. Which tool shows which components are checked and how long change detection takes?
Correct answer: The Angular DevTools profiler
The profiler records change detection cycles per component, which helps find components that should be OnPush, heavy template expressions and zone pollution.
33. What does Angular do with a value bound to
[innerHTML]?Correct answer: Sanitizes it, removing scripts and dangerous URLs
Angular treats all values as untrusted by default and sanitizes them by context (HTML, style, URL, resource URL). It logs a warning in dev mode when it strips content.
34. When is
DomSanitizer.bypassSecurityTrustHtml()dangerous?Correct answer: When users can influence the value, since it opens the way to XSS
Bypass only for content you fully control, or sanitize it yourself first with a trusted library. Enable Trusted Types and a strict CSP for defense in depth.
35. How does
HttpClienthelp protect against CSRF?Correct answer: It copies the
XSRF-TOKENcookie into a request headerThe server must set the cookie and verify the header. Angular doesn't add the header to GET/HEAD requests or absolute URLs to avoid leaking the token to other domains.
36. What is the data flow in NgRx Store?
Correct answer: Actions go to reducers, and selectors read the new state
It is the Redux pattern adapted to Angular: a single immutable state tree, pure reducers, memoized selectors and effects for async work. It shines in large teams with complex shared state.
37. Why are NgRx selectors created with
createSelectormemoized?Correct answer: They return the same reference until their inputs change
Selectors compose (
selectVisibleTodosfromselectTodosandselectFilter) and only recompute when an input slice changes, which keeps OnPush components efficient.38. What is an NgRx effect?
Correct answer: A stream that reacts to actions and runs side effects
Effects keep reducers pure. A typical one:
loadUsers→switchMapto the API →loadUsersSuccessorloadUsersFailure, choosing the flattening operator deliberately.39. What is NgRx SignalStore?
export const TodosStore = signalStore( withState({ todos: [] as Todo[], filter: "all" }), withComputed(({ todos }) => ({ count: computed(() => todos().length) })), withMethods((store) => ({ setFilter: (filter: string) => patchState(store, { filter }) })), );Correct answer: A lightweight signal-based store provided like a service
SignalStore has no actions or reducers by default: state is a set of signals, updated with
patchState. It can be provided in root or per component and extended with custom features.40. When is a plain service with signals enough instead of a state library?
Correct answer: When state stays within one feature and needs no strict event log
A service exposing read-only signals (
asReadonly()) and methods that update them covers many apps. Add a library when cross-feature state, debugging needs or team conventions justify it.41. How are micro-frontends commonly built with Angular?
Correct answer: With Module Federation or Native Federation, loading remotely built apps or components at runtime
Each team builds and deploys independently, and the shell loads remotes via the router. The cost: shared dependency versions, consistent UX and more complex debugging.
42. What does
ng update @angular/core @angular/clido besides bumping versions?Correct answer: Runs migration schematics that update your code for breaking changes
Update one major version at a time and follow the Angular Update Guide. There are also optional migrations, e.g. to control flow, signal inputs or
inject().43. How do you centrally report uncaught errors in an Angular app?
Correct answer: Provide a custom
ErrorHandlerthat sends them out{ provide: ErrorHandler, useClass: SentryErrorHandler }receives errors from templates, lifecycle hooks and event handlers. HTTP errors are better handled in interceptors.44. What are Angular Elements?
Correct answer: Angular components packaged as native Custom Elements
customElements.define('my-widget', createCustomElement(Widget, { injector })). Useful for embedding widgets in CMS pages or gradually migrating legacy apps.45. What is the main trade-off of Angular's built-in i18n (
@angular/localize)?Correct answer: Each locale is a separate build, and switching reloads the page
You mark text with
i18nattributes and$localize, extract messages and build per locale. Runtime libraries like Transloco allow switching languages without a reload at some runtime cost.46. What are component harnesses for?
Correct answer: A test API that drives a component and hides its DOM
const button = await loader.getHarness(MatButtonHarness)keeps tests working when the internal markup changes. Angular Material ships harnesses, and you can write your own with the CDK.47. Why doesn't this test replace the service used by the component?
@Component({ providers: [EditorState] }) class Editor {} TestBed.configureTestingModule({ providers: [{ provide: EditorState, useValue: fake }] });Correct answer: Component-level providers win; use
TestBed.overrideComponentThe component's element injector is closer than the test module's injector.
TestBed.overrideComponent(Editor, { set: { providers: [{ provide: EditorState, useValue: fake }] } })fixes it.48. How do you test guards and routed components together?
Correct answer: With
RouterTestingHarness, navigating to a URLconst harness = await RouterTestingHarness.create(); await harness.navigateByUrl('/admin');runs real guards and resolvers withprovideRouter(routes)in the test.49. Why are nested
subscribecalls considered an anti-pattern?this.route.paramMap.subscribe((p) => { this.api.load(p.get("id")!).subscribe((data) => (this.data = data)); });Correct answer: Inner subscriptions aren't cancelled, which causes races and leaks
paramMap.pipe(switchMap((p) => this.api.load(p.get('id')!)))cancels stale requests when the param changes and gives one subscription to manage (or none, withasync/toSignal).50. What is the difference between a cold and a hot Observable?
Correct answer: Cold starts its producer per subscriber; hot shares one
Operators like
shareandshareReplayturn a cold Observable into a multicast one. Knowing the difference explains duplicate requests and missed values.51. Why does
takeUntilDestroyed()throw when called inside a click handler?onClick() { this.data$.pipe(takeUntilDestroyed()).subscribe(); }Correct answer: Without arguments it needs an injection context
Inject
DestroyRefin a field and calltakeUntilDestroyed(this.destroyRef). The same rule applies totoSignalandeffect.52. What is the risk of
shareReplay(1)withoutrefCount: trueon a long-lived source?Correct answer: The source stays subscribed after everyone leaves, which can leak
shareReplay({ bufferSize: 1, refCount: true })unsubscribes from the source when the subscriber count drops to zero. For one-shot HTTP calls it matters less.53. In what order do functional interceptors process a request and its response?
provideHttpClient(withInterceptors([authInterceptor, loggingInterceptor]))Correct answer: Requests go in listed order, responses in reverse
Each interceptor wraps the next one. Put auth before logging if the log should include the final headers, and retry logic close to the backend.
54. How do you configure per-route rendering (SSR, prerender, client-only) in Angular SSR?
export const serverRoutes: ServerRoute[] = [ { path: '', renderMode: RenderMode.Prerender }, { path: 'dashboard/**', renderMode: RenderMode.Client }, { path: '**', renderMode: RenderMode.Server }, ];Correct answer: Define server routes with a
renderModefor each pathMarketing pages can be prerendered at build time, authenticated areas rendered on the client, and the rest on demand. Prerendered dynamic routes need
getPrerenderParams.55. How can SSR code read the incoming HTTP request (e.g. a cookie)?
Correct answer: Inject the
REQUESTtoken, which isnullin the browserRESPONSE_INITlets SSR set the status or headers. Code must handlenull, because the same component runs in the browser.56. How do you make SSR wait for async work that isn't an HTTP request (e.g. a timer-based init)?
const pending = inject(PendingTasks); pending.run(() => loadWidgetConfig());Correct answer: Register it with
PendingTasks, so the app isn't stable yetSSR serializes the page once the app is stable. Without zone.js, Angular can't see arbitrary promises, so long-lived work must be tracked explicitly.
57. When is
ngSkipHydrationon a component a reasonable workaround?Correct answer: When a third-party widget touches the DOM and can't be fixed yet
Skipping hydration loses its benefits for that subtree and can cause a flash. Prefer fixing direct DOM manipulation by using Angular APIs.
58. How do you use a CSP nonce with Angular's inline styles?
Correct answer: Set
ngCspNonceon the root element with a per-request nonceAngular inserts component styles at runtime. The nonce must be generated per request on the server and match the
Content-Security-Policyheader.59. What does Angular's Trusted Types support help with?
Correct answer: Only sanitized or trusted values can reach sinks like
innerHTMLWith a
require-trusted-types-for 'script'CSP, raw string assignments to sinks fail, so any XSS bypass in custom code becomes visible.60. What does
createEntityAdapterfrom@ngrx/entitygive you?Correct answer: Normalized
{ ids, entities }state with CRUD helpersNormalized collections make updates by id cheap and avoid duplicate items.
sortComparerkeepsidsordered.61. What does
createFeatureadd in NgRx?Correct answer: Pairs a name with a reducer and generates selectors
Less boilerplate and consistent selector names. Extra derived selectors can be added through
extraSelectors.62. What are Signal Forms in recent Angular versions?
model = signal({ email: '', password: '' }); loginForm = form(this.model, (p) => { required(p.email); email(p.email); });Correct answer: An experimental forms API built on a signal model
Field state (
value,valid,touched,errors) is exposed as signals. As an experimental API it may change, so weigh that before adopting it widely.63. Why might
RouteReuseStrategybe customized?Correct answer: To keep a component alive and reattach it on return
Detached views keep their state and subscriptions, so you must manage memory and stale data yourself.
64. How do you show a global progress bar while a lazy route is loading?
inject(Router).events.subscribe((e) => { if (e instanceof NavigationStart) this.loading.set(true); if (e instanceof NavigationEnd || e instanceof NavigationCancel || e instanceof NavigationError) this.loading.set(false); });Correct answer: Start on
NavigationStart, stop on end, cancel or errorIf cancel and error events are ignored, a blocked guard or a failed chunk leaves the spinner on forever.
65. What is the main benefit of using
inject()over constructor parameters in base classes?Correct answer: Subclasses needn't repeat the parent's dependencies
Field initializers with
inject()are inherited. It also works in functions like guards and resolvers.66. What does
providedIn: 'platform'mean?Correct answer: One instance shared by all Angular apps on the page
It's rare. Most services should be
'root'so each app (and each SSR request) gets its own instance.67. In Angular SSR, where does user data typically leak between requests?
Correct answer: In module-level mutable variables of the Node process
Avoid module-level mutable state (like
let cache = {}outside a class); keep state in services so it's scoped per request.68. When does
effectbeatcomputed, and when is it a smell?Correct answer: Effects fit outside work like logging; setting signals is a smell
Derived values should be
computedorlinkedSignal, which stay consistent and lazy; effects writing signals cause extra cycles.69. Why does changing an object's property inside a signal not update the view?
user = signal({ name: 'Ann' }); rename() { this.user().name = 'Bob'; }Correct answer: The reference didn't change, so consumers weren't notified
Write
this.user.update((u) => ({ ...u, name: 'Bob' })). Signals compare withObject.isby default.70. How do you analyse which dependencies make the main bundle large?
Correct answer: Build with
--stats-jsonand open it in a bundle analyzerCommon culprits are heavy libraries imported eagerly, barrel files pulling in extra code and missing lazy routes or
@defer.71. How do you keep a large Angular codebase from creating circular or wrong-direction imports between features?
Correct answer: Enforce boundaries with lint rules and a public API per feature
Clear layers (feature → data-access → ui → util) and enforced boundaries keep lazy chunks small and refactoring safe.
72. Why are template-driven forms harder to scale than reactive forms in complex screens?
Correct answer: State lives in the template, so dynamic fields are harder to test
Reactive (or signal) forms keep the model in TypeScript, which suits dynamic arrays, typed values and testing without the DOM.
73. What does
@defer (hydrate on interaction)do with incremental hydration?Correct answer: Renders on the server, hydrates when the user interacts
Users see the content immediately while the JavaScript cost is postponed. Event replay keeps the interaction that triggered hydration.
74. Why can a frequent
mousemovelistener hurt a zone-based app but less so a zoneless one?Correct answer: With zone.js every event checks the app; zoneless needs a signal
In zone-based apps such listeners are registered via
runOutsideAngular. In zoneless apps, avoid updating signals on every event if nothing visible changes.75. What is the typical architecture for NgRx effects that handle many concurrent requests to the same endpoint?
Correct answer: Choose the flattening operator per case:
switchMap,concatMapand so onswitchMapon writes can cancel saves and lose data. The operator choice is a business decision about concurrency.