Angular Middle 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. What changes when a component uses
ChangeDetectionStrategy.OnPush?Correct answer: It is checked only when marked dirty, for example by a new input reference
With the default strategy every component is checked on each change detection run. OnPush skips whole subtrees that were not marked, which is the main runtime optimization in zone-based apps.
2. Why doesn't this OnPush child update after the parent runs
addItem()?// parent items = [{ id: 1 }]; addItem() { this.items.push({ id: 2 }); } // template: <app-list [items]="items" />Correct answer: The array was mutated, so the input reference stayed the same
OnPush compares inputs by reference. Create a new array (
this.items = [...this.items, item]) or keep the list in a signal and update it immutably.3. When do you need
ChangeDetectorRef.markForCheck()?Correct answer: In OnPush, when a manual
subscribesets a plain fieldmarkForCheckmarks the component and its ancestors so they are checked in the next run. Theasyncpipe and signals do this automatically, which is why they are preferred over manual subscriptions.4. What does
ExpressionChangedAfterItHasBeenCheckedErrormean?Correct answer: A bound value changed again during the same check pass
In development Angular runs a second check to make sure data flows one way. It is typically caused by changing parent state in a child's
ngAfterViewInitor by getters that return new values each time. Fix the data flow instead of hiding it withsetTimeout.5. How do signals improve change detection compared to plain fields?
Correct answer: Angular marks only the components whose templates read the signal
A signal read in a template registers the view as a consumer. When the signal changes, that view is marked dirty - even in an OnPush component - without relying on Zone.js guessing that something might have changed.
6. Which is the best way to display data from an Observable in an OnPush component?
Correct answer: The
asyncpipe ortoSignal(), both of which update the view correctlyA manual subscription assigning a plain field won't be picked up by OnPush without
markForCheck, and it also needs manual cleanup.asyncandtoSignalhandle both concerns.7. What does
linkedSignalsolve?options = input.required<string[]>(); selected = linkedSignal(() => this.options()[0]);Correct answer: A writable signal that resets when its source changes
The user can
selected.set(...)a different option, but whenoptionschanges the selection is recomputed. BeforelinkedSignal, this needed aneffectthat wrote into another signal.8. What does
untracked()do inside acomputedoreffect?effect(() => { const user = this.user(); untracked(() => this.logger.log(user, this.settings())); });Correct answer: Reads signals without making them dependencies
Every signal read inside a reactive context becomes a dependency.
untrackedlimits re-runs to the signals that should actually trigger the side effect.9. How do you turn an Observable into a signal?
Correct answer:
toSignal(obs$, { initialValue: [] })toSignalsubscribes immediately and unsubscribes when the injection context is destroyed. WithoutinitialValuethe signal type includesundefineduntil the first emission.10. What does
toObservable(sig)let you do?Correct answer: Apply operators like
switchMapto signal changesA common pattern:
toSignal(toObservable(this.query).pipe(debounceTime(300), switchMap((q) => this.api.search(q)))). Signals hold state; RxJS is good at time-based and cancellable async flows.11. What does
model()create?export class Rating { value = model(0); set(v: number) { this.value.set(v); } } // parent: <app-rating [(value)]="rating" />Correct answer: A writable input signal with two-way binding
Writing to a model signal emits a
valueChangeevent, so[(value)]keeps the parent in sync. The parent can bind a plain field or a writable signal.12. What is an input
transformused for?disabled = input(false, { transform: booleanAttribute }); // usage: <app-button disabled />Correct answer: To convert the bound value before the component gets it
Without the transform,
<app-button disabled />would pass an empty string. Angular shipsbooleanAttributeandnumberAttribute; transforms must be pure functions.13. Which operator suits a search-as-you-type request so that only the latest query result is shown?
Correct answer:
switchMapswitchMapunsubscribes from the previous inner Observable (cancelling the HTTP request) when a new value arrives, so slow old responses can't overwrite newer results.14. Which operator should handle a "Pay" button so double clicks don't send duplicate requests?
Correct answer:
exhaustMapexhaustMapignores new source values while the current inner Observable is still running.switchMapwould cancel the first payment request,mergeMapwould send both.15. Which operator keeps several save requests strictly in order, one after another?
Correct answer:
concatMapconcatMapqueues values and subscribes to the next inner Observable only after the previous one completes. This matters when the server must apply updates in order.16. What is
mergeMapbest for?Correct answer: Running independent inner requests in parallel
mergeMapsubscribes to every inner Observable immediately; results arrive in completion order. Its second argument limits concurrency, e.g.mergeMap(upload, 3).17. Why add
distinctUntilChanged()afterdebounceTime(300)in a search box?Correct answer: To skip the request when the text hasn't changed
Typing "ab", deleting "b" and typing it again within the debounce window produces "ab" again.
distinctUntilChangeddrops that duplicate beforeswitchMapsends a request.18. How does
BehaviorSubjectdiffer fromSubject?Correct answer: It stores the current value and gives it to new subscribers
A plain
Subjectemits only future values, so late subscribers miss earlier ones.BehaviorSubject(andgetValue()) was the classic way to hold service state; in modern Angular asignaloften replaces it.19. Why does this code send two HTTP requests, and how do you fix it?
user$ = this.http.get<User>("/api/me"); // template: // {{ (user$ | async)?.name }} {{ (user$ | async)?.email }}Correct answer: The Observable is cold, so each
asyncsubscribes on its own; useshareReplay(1)Every subscription runs the request. Use
@if (user$ | async; as user)once, convert to a signal withtoSignal, or share the stream withshareReplay({ bufferSize: 1, refCount: true }).20. Why should
catchErrorbe placed insideswitchMapin a long-lived stream?this.query$.pipe( switchMap((q) => this.api.search(q).pipe(catchError(() => of([])))), );Correct answer: An error ends the stream it reaches, so catch it on the inner one
If the error reaches the outer stream, it terminates and the search box stops working after the first failure. Handle errors per request and return a fallback value.
21. What is the modern way to unsubscribe from an Observable when a component is destroyed?
constructor() { interval(1000).pipe(takeUntilDestroyed()).subscribe((n) => this.tick.set(n)); }Correct answer:
takeUntilDestroyed()fromrxjs-interopIt uses
DestroyRefunder the hood. Called without arguments it needs an injection context; elsewhere pass aDestroyRef. HTTP requests complete by themselves, butinterval,valueChangesand router events don't.22. What happens when a component lists a service in its
providers?@Component({ selector: "app-editor", providers: [EditorState] })Correct answer: Each
app-editorgets its ownEditorState, shared with its childrenComponent providers create an element injector. Each component instance and its subtree get a separate instance, which is great for per-widget state; it is destroyed with the component.
23. Why use an
InjectionToken?export const API_URL = new InjectionToken<string>("API_URL"); // providers: [{ provide: API_URL, useValue: "https://api.example.com" }] // usage: private apiUrl = inject(API_URL);Correct answer: To inject values with no class, like config objects
Interfaces disappear at runtime, so they can't be DI tokens. An
InjectionTokenis a unique runtime key that also carries the TypeScript type.24. What is the difference between
useClass,useValue,useFactoryanduseExisting?Correct answer: New class instance, ready value, factory function, alias of a token
For example
{ provide: Logger, useClass: ConsoleLogger }swaps an implementation, anduseFactory: () => inject(Config).debug ? new DebugLogger() : new Logger()decides at runtime.25. What does
multi: truedo in a provider?Correct answer: Providers of one token are collected into an array
Multi-providers let many parts of the app contribute to one extension point (validators, initializers).
inject(TOKEN)returns an array of all contributed values.26. How do you inject a dependency that might not be provided?
Correct answer:
inject(Analytics, { optional: true })Without
optional, Angular throwsNullInjectorErrorwhen no provider is found. Other options includeself,skipSelfandhost, which limit where the resolution looks.27. What happens when a lazy route declares
providers?{ path: "admin", providers: [AdminApi], loadChildren: () => import("./admin.routes") }Correct answer: Angular creates a separate injector for that route subtree
The services live only under
/admin, keep feature code out of the root, and are created when the route is first activated.28. How do you lazy-load a standalone component for a route?
Correct answer:
loadComponent: () => import('./settings').then((m) => m.Settings)The bundler puts the component in its own chunk, downloaded on first navigation. For a group of routes use
loadChildrenthat returns aRoutesarray.29. What does a functional guard return to redirect the user?
export const authGuard: CanActivateFn = () => { const auth = inject(AuthService); const router = inject(Router); return auth.isLoggedIn() ? true : router.createUrlTree(["/login"]); };Correct answer: A
UrlTree, which cancels the navigation and redirectsGuards may return a boolean,
UrlTree,RedirectCommand, or an Observable/Promise of these. Returning aUrlTreeavoids racing navigations that happen when you callnavigateinside a guard.30. How does
canMatchdiffer fromcanActivate?Correct answer:
canMatchdecides if the route is considered at all, before lazy code loadsWith
canMatchyou can have two routes with the same path for different roles (/dashboardfor admins and users), and an unauthorized user doesn't download the admin chunk.31. What is a resolver used for?
Correct answer: Loading data before the route activates
A
ResolveFnreturns data (or an Observable/Promise). The trade-off: navigation waits for the data, so for slow requests it is often better to navigate immediately and show a loading state.32. What does
withComponentInputBinding()enable?provideRouter(routes, withComponentInputBinding()); // route: users/:id export class UserPage { id = input.required<string>(); }Correct answer: Route params are bound to inputs with matching names
Instead of injecting
ActivatedRouteand subscribing toparamMap, the component simply declares an input. It updates when you navigate between/users/1and/users/2while staying on the same component.33. How do you warn the user before leaving a page with unsaved changes?
Correct answer: A
canDeactivateguard that asks for confirmationCanDeactivateFn<EditPage>receives the component instance and can returnconfirm(...).beforeunloadonly covers closing or reloading the tab, not router navigation.34. Why does a component not re-run
ngOnInitwhen navigating from/users/1to/users/2?Correct answer: The router reuses the instance when only params change
Read the param reactively: an input with
withComponentInputBinding, orroute.paramMapcombined withswitchMap. Reading the snapshot once inngOnInitshows stale data.35. How do you write a custom synchronous validator?
export const noSpaces: ValidatorFn = (control) => /\s/.test(control.value ?? "") ? { noSpaces: true } : null;Correct answer: A function that returns an errors object or
nullAdd it to the control's
validators. The error key appears incontrol.errors, so the template can checkcontrol.hasError('noSpaces').36. Where should a "passwords must match" validator be attached?
Correct answer: To the
FormGroupthat contains both fieldsA group-level validator receives the group and can read both controls. The error then appears in
form.errors, not in the individual controls.37. How do async validators behave in Angular forms?
Correct answer: They run after sync validators pass, with status
PENDINGTypical use is checking whether a username is taken. Combine with
updateOn: 'blur'or debouncing in the validator to avoid a request per keystroke.38. What is
FormArrayfor?Correct answer: A dynamic list of controls the user can add and remove
You
pushandremoveAtcontrols at runtime and render them with@forand[formGroupName]="$index". The array's value is an array of the controls' values.39. What does
nonNullable: truechange in typed reactive forms?Correct answer:
reset()restores the initial value, so the type has nonullBy default a control's type is
T | nullbecausereset()sets it tonull.NonNullableFormBuilder(inject(FormBuilder).nonNullable) applies this to every control.40. What does implementing
ControlValueAccessorallow?Correct answer: A custom component works with
formControlNamelike an inputImplement
writeValue,registerOnChange,registerOnTouched(and optionallysetDisabledState) and provideNG_VALUE_ACCESSOR. The forms API then talks to your component through these methods.41. How do you get a reference to a child element or component in the class?
searchInput = viewChild.required<ElementRef<HTMLInputElement>>("search"); focus() { this.searchInput().nativeElement.focus(); }Correct answer: With signal queries:
viewChild()/viewChildren()Signal queries update automatically when the element appears or disappears (e.g. inside
@if).contentChild/contentChildrenquery projected content instead of the component's own view.42. How do you create several named slots for projected content?
<!-- dialog.html --> <header><ng-content select="[dialog-title]" /></header> <main><ng-content /></main>Correct answer: With the
selectattribute on<ng-content>The selector can be an attribute, element or class. Note that projected content is always created by the parent, even when the slot is hidden by
@ifin the child.43. What does this
@deferblock do?@defer (on viewport) { <app-comments /> } @placeholder { <p>Comments</p> }Correct answer: Loads
app-commentsonly when the placeholder enters the viewportThe deferred component's code goes into a separate chunk. Other triggers are
on idle(default),on interaction,on hover,on timer(2s)andwhen condition;prefetch on ...downloads earlier.44. What is the difference between pure and impure pipes?
Correct answer: A pure pipe re-runs only when its arguments change; an impure one runs on every check
Pipes are pure by default, which makes them cheap.
pure: falseis needed when the output depends on internal mutations (likeasync), but it is costly when the work is heavy.45. What is the recommended way to bind to the host element of a component?
@Component({ selector: "app-tab", host: { role: "tab", "[class.active]": "active()", "(click)": "select()" }, })Correct answer: The
hostproperty in the decorator metadataThe Angular style guide prefers the
hostobject over the@HostBinding/@HostListenerdecorators: everything about the host is in one place and the expressions are type-checked.46. What is an attribute directive?
@Directive({ selector: "[appAutofocus]" }) export class Autofocus { private el = inject(ElementRef); constructor() { afterNextRender(() => this.el.nativeElement.focus()); } }Correct answer: A class that adds behavior to an existing element
Directives are used as attributes (
<input appAutofocus />).afterNextRenderruns only in the browser after rendering, so the code is safe with SSR.47. How do you add an auth header to every request?
export const authInterceptor: HttpInterceptorFn = (req, next) => { const token = inject(AuthService).token(); return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req); }; // provideHttpClient(withInterceptors([authInterceptor]))Correct answer: With a functional interceptor that clones the request - requests are immutable
HttpRequestis immutable, so interceptors callclone. Interceptors run in the order they are listed and can also handle errors, retries, logging and caching.48. How do you test a service that uses
HttpClientwithout real network calls?Correct answer: Use
provideHttpClientTesting()andHttpTestingControllerhttpTesting.expectOne('/api/users').flush([...])returns a fake response, andverify()inafterEachensures no unexpected requests were made.49. Why call
fixture.detectChanges()in a component test?Correct answer: To run change detection so the template shows the state
After changing component state in a test, you update the DOM with
detectChanges()(orawait fixture.whenStable()), then query elements viafixture.nativeElementordebugElement.50. When migrating to standalone, how do you keep using an NgModule-based library?
Correct answer: Add the NgModule to the component's
importsStandalone and NgModule code interoperate. The CLI also has a schematic (
ng generate @angular/core:standalone) that migrates an existing project step by step.51. How does
forkJoindiffer fromcombineLatest?Correct answer:
forkJoinemits once when all complete,combineLateston every emissionforkJoinfits parallel HTTP requests.combineLatestfits long-lived streams like filters plus data; with signals,computedoften replaces it.52. How do you get a single value from an Observable with
async/await?const user = await firstValueFrom(this.http.get<User>('/api/me'));Correct answer: With
firstValueFrom(orlastValueFrom) from RxJStoPromise()is deprecated.firstValueFromresolves on the first value and unsubscribes; it rejects if the stream completes without values.53. How do you retry a failed HTTP request three times with a delay?
this.http.get('/api/data').pipe(retry({ count: 3, delay: 1000 }))Correct answer: Use the
retryoperator withcountanddelayRetry only idempotent requests (like GET).
delaycan be a function for exponential backoff.54. How does
ReplaySubject(3)differ fromBehaviorSubject?Correct answer: It replays the last 3 values and needs no initial value
BehaviorSubjectalways has a current value (one) and requires an initial value.ReplaySubjectbuffers a configurable number of values.55. What does the
scanoperator do?clicks$.pipe(scan((total) => total + 1, 0))Correct answer: Accumulates state and emits each intermediate result
reducewaits for completion;scanemits after every value, which suits counters or a reducer-like state stream.56. How can a single request skip a functional interceptor (e.g. the auth header)?
export const SKIP_AUTH = new HttpContextToken(() => false); this.http.get(url, { context: new HttpContext().set(SKIP_AUTH, true) });Correct answer: Pass an
HttpContexttoken and check it in the interceptorThe interceptor reads
req.context.get(SKIP_AUTH)and forwards the request unchanged. It's cleaner than matching URLs.57. What does
provideHttpClient(withFetch())change?Correct answer:
HttpClientuses the Fetch API instead ofXMLHttpRequestThe API of
HttpClientstays the same. Fetch works natively in Node.js, which is why it's preferred on the server.58. How do you render the same template fragment in several places of a component?
<ng-template #price let-value>{{ value | currency }}</ng-template> <ng-container *ngTemplateOutlet="price; context: { $implicit: total }" />Correct answer:
<ng-template>plusngTemplateOutletA template can also be passed as an input to a child, which lets the parent customize how items are rendered.
59. What does
hostDirectivesin a component or directive do?@Component({ selector: 'app-menu-item', hostDirectives: [CdkMenuItem], })Correct answer: Applies other directives to the host element, without inheritance
Inputs and outputs of host directives are not exposed unless listed explicitly. It's the directive composition API.
60. How do you measure a DOM element's size after the component renders?
constructor() { afterNextRender(() => { this.height = this.el.nativeElement.offsetHeight; }); }Correct answer: In
afterNextRender, once the DOM is updatedThese callbacks don't run during SSR, which makes them a safe place for browser-only DOM work.
61. How do you register cleanup code from a service or a function without
ngOnDestroy?const destroyRef = inject(DestroyRef); destroyRef.onDestroy(() => socket.close());Correct answer: Inject
DestroyRefand callonDestroyDestroyRefbelongs to the current injector: a component, a route's environment, or the app.takeUntilDestroyedis built on it.62. How do you expose a signal from a service without letting components change it?
private readonly _items = signal<Item[]>([]); readonly items = this._items.asReadonly();Correct answer: Keep it private and expose
asReadonly()Components read
items(), and changes go through the service's methods. This keeps updates in one place.63. How do you lazy-load a group of child routes?
{ path: 'admin', loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES) }Correct answer: Use
loadChildrenthat imports a routes arrayThe whole feature (components, services from route
providers) goes into a separate chunk loaded on first visit.64. How do you animate transitions between routes with the browser's View Transitions API?
provideRouter(routes, withViewTransitions())Correct answer: Enable
withViewTransitions()inprovideRouterBrowsers without View Transitions support navigate as usual. The
::view-transition-*pseudo-elements control the animation.65. What does
redirectToas a function allow?{ path: 'profile', redirectTo: () => inject(Auth).isAdmin() ? '/admin' : '/me' }Correct answer: Computing the redirect target at navigation time
It can also read route params and return a
UrlTree. For checks that can deny access, guards are still clearer.66. How do you give an
InjectionTokena default value without adding providers?export const PAGE_SIZE = new InjectionToken<number>('PAGE_SIZE', { providedIn: 'root', factory: () => 20, });Correct answer: The
factoryoption withprovidedIn: 'root'The factory can call
inject()for other dependencies. Any provider for the token still overrides the default.67. How do you create a component dynamically and set its inputs?
const ref = this.vcr.createComponent(Toast); ref.setInput('message', 'Saved');Correct answer: Use
ViewContainerRef.createComponentandComponentRef.setInputsetInputworks with signal inputs and marks OnPush components for check.NgComponentOutletcovers simple template cases.68. Which test runner do new Angular CLI projects use by default since v21?
Correct answer: Vitest
Karma was deprecated. Vitest runs tests faster and can run them in Node with a DOM emulation or in a real browser.
69. How do you test an OnPush component after changing a signal input?
fixture.componentRef.setInput('user', mockUser); fixture.detectChanges();Correct answer:
fixture.componentRef.setInput(), thendetectChanges()Signal inputs are read-only from the class, and
setInputgoes through the same path as a parent binding, including OnPush marking.70. What does
toSignal(obs$, { initialValue: [] })change compared totoSignal(obs$)?Correct answer: It starts with
[], so the type has noundefinedFor Observables that emit synchronously (like a
BehaviorSubject),requireSync: trueremovesundefinedwithout an initial value.71. What is a
rxResource(orresource) useful for compared to manual subscribe ineffect?Correct answer: Loading data that depends on signals, with status and cancellation
When the params signal changes, the previous load is aborted. Writing this with
effectand flags is error-prone.72. Why avoid
subscribeinside a component just to copy values into fields?ngOnInit() { this.service.users$.subscribe((u) => (this.users = u)); }Correct answer: It needs manual unsubscribing and may not refresh OnPush views
Declarative bindings tie the subscription to the view's lifetime and notify change detection automatically.
73. What is
@defer (on viewport; prefetch on idle)for?Correct answer: Loading the code when idle, rendering it in the viewport
Separating prefetch and render triggers makes the block appear instantly when scrolled to, without loading it upfront.
74. How do you pass a template from a parent to customize how a child renders each item?
<app-list [items]="users" [itemTemplate]="row" /> <ng-template #row let-user>{{ user.name }}</ng-template>Correct answer: Pass a
TemplateRefinput and usengTemplateOutlet<ng-content>projects content once; a template can be stamped out many times with a different context for each item.75. How do you render a list of 10,000 rows without creating 10,000 DOM nodes?
<cdk-virtual-scroll-viewport itemSize="48" class="h-96"> <div *cdkVirtualFor="let row of rows">{{ row.name }}</div> </cdk-virtual-scroll-viewport>Correct answer: Virtual scrolling from the Angular CDK
trackhelps reuse DOM nodes but doesn't reduce their number. Virtual scrolling keeps the DOM small; pagination is another option.