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. 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. 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. 3. When do you need ChangeDetectorRef.markForCheck()?

    Correct answer: In OnPush, when a manual subscribe sets a plain field

    markForCheck marks the component and its ancestors so they are checked in the next run. The async pipe and signals do this automatically, which is why they are preferred over manual subscriptions.

  4. 4. What does ExpressionChangedAfterItHasBeenCheckedError mean?

    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 ngAfterViewInit or by getters that return new values each time. Fix the data flow instead of hiding it with setTimeout.

  5. 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. 6. Which is the best way to display data from an Observable in an OnPush component?

    Correct answer: The async pipe or toSignal(), both of which update the view correctly

    A manual subscription assigning a plain field won't be picked up by OnPush without markForCheck, and it also needs manual cleanup. async and toSignal handle both concerns.

  7. 7. What does linkedSignal solve?

    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 when options changes the selection is recomputed. Before linkedSignal, this needed an effect that wrote into another signal.

  8. 8. What does untracked() do inside a computed or effect?

    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. untracked limits re-runs to the signals that should actually trigger the side effect.

  9. 9. How do you turn an Observable into a signal?

    Correct answer: toSignal(obs$, { initialValue: [] })

    toSignal subscribes immediately and unsubscribes when the injection context is destroyed. Without initialValue the signal type includes undefined until the first emission.

  10. 10. What does toObservable(sig) let you do?

    Correct answer: Apply operators like switchMap to signal changes

    A 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. 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 valueChange event, so [(value)] keeps the parent in sync. The parent can bind a plain field or a writable signal.

  12. 12. What is an input transform used 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 ships booleanAttribute and numberAttribute; transforms must be pure functions.

  13. 13. Which operator suits a search-as-you-type request so that only the latest query result is shown?

    Correct answer: switchMap

    switchMap unsubscribes from the previous inner Observable (cancelling the HTTP request) when a new value arrives, so slow old responses can't overwrite newer results.

  14. 14. Which operator should handle a "Pay" button so double clicks don't send duplicate requests?

    Correct answer: exhaustMap

    exhaustMap ignores new source values while the current inner Observable is still running. switchMap would cancel the first payment request, mergeMap would send both.

  15. 15. Which operator keeps several save requests strictly in order, one after another?

    Correct answer: concatMap

    concatMap queues 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. 16. What is mergeMap best for?

    Correct answer: Running independent inner requests in parallel

    mergeMap subscribes to every inner Observable immediately; results arrive in completion order. Its second argument limits concurrency, e.g. mergeMap(upload, 3).

  17. 17. Why add distinctUntilChanged() after debounceTime(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. distinctUntilChanged drops that duplicate before switchMap sends a request.

  18. 18. How does BehaviorSubject differ from Subject?

    Correct answer: It stores the current value and gives it to new subscribers

    A plain Subject emits only future values, so late subscribers miss earlier ones. BehaviorSubject (and getValue()) was the classic way to hold service state; in modern Angular a signal often replaces it.

  19. 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 async subscribes on its own; use shareReplay(1)

    Every subscription runs the request. Use @if (user$ | async; as user) once, convert to a signal with toSignal, or share the stream with shareReplay({ bufferSize: 1, refCount: true }).

  20. 20. Why should catchError be placed inside switchMap in 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. 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() from rxjs-interop

    It uses DestroyRef under the hood. Called without arguments it needs an injection context; elsewhere pass a DestroyRef. HTTP requests complete by themselves, but interval, valueChanges and router events don't.

  22. 22. What happens when a component lists a service in its providers?

    @Component({ selector: "app-editor", providers: [EditorState] })

    Correct answer: Each app-editor gets its own EditorState, shared with its children

    Component 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. 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 InjectionToken is a unique runtime key that also carries the TypeScript type.

  24. 24. What is the difference between useClass, useValue, useFactory and useExisting?

    Correct answer: New class instance, ready value, factory function, alias of a token

    For example { provide: Logger, useClass: ConsoleLogger } swaps an implementation, and useFactory: () => inject(Config).debug ? new DebugLogger() : new Logger() decides at runtime.

  25. 25. What does multi: true do 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. 26. How do you inject a dependency that might not be provided?

    Correct answer: inject(Analytics, { optional: true })

    Without optional, Angular throws NullInjectorError when no provider is found. Other options include self, skipSelf and host, which limit where the resolution looks.

  27. 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. 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 loadChildren that returns a Routes array.

  29. 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 redirects

    Guards may return a boolean, UrlTree, RedirectCommand, or an Observable/Promise of these. Returning a UrlTree avoids racing navigations that happen when you call navigate inside a guard.

  30. 30. How does canMatch differ from canActivate?

    Correct answer: canMatch decides if the route is considered at all, before lazy code loads

    With canMatch you can have two routes with the same path for different roles (/dashboard for admins and users), and an unauthorized user doesn't download the admin chunk.

  31. 31. What is a resolver used for?

    Correct answer: Loading data before the route activates

    A ResolveFn returns 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. 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 ActivatedRoute and subscribing to paramMap, the component simply declares an input. It updates when you navigate between /users/1 and /users/2 while staying on the same component.

  33. 33. How do you warn the user before leaving a page with unsaved changes?

    Correct answer: A canDeactivate guard that asks for confirmation

    CanDeactivateFn<EditPage> receives the component instance and can return confirm(...). beforeunload only covers closing or reloading the tab, not router navigation.

  34. 34. Why does a component not re-run ngOnInit when navigating from /users/1 to /users/2?

    Correct answer: The router reuses the instance when only params change

    Read the param reactively: an input with withComponentInputBinding, or route.paramMap combined with switchMap. Reading the snapshot once in ngOnInit shows stale data.

  35. 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 null

    Add it to the control's validators. The error key appears in control.errors, so the template can check control.hasError('noSpaces').

  36. 36. Where should a "passwords must match" validator be attached?

    Correct answer: To the FormGroup that contains both fields

    A group-level validator receives the group and can read both controls. The error then appears in form.errors, not in the individual controls.

  37. 37. How do async validators behave in Angular forms?

    Correct answer: They run after sync validators pass, with status PENDING

    Typical use is checking whether a username is taken. Combine with updateOn: 'blur' or debouncing in the validator to avoid a request per keystroke.

  38. 38. What is FormArray for?

    Correct answer: A dynamic list of controls the user can add and remove

    You push and removeAt controls at runtime and render them with @for and [formGroupName]="$index". The array's value is an array of the controls' values.

  39. 39. What does nonNullable: true change in typed reactive forms?

    Correct answer: reset() restores the initial value, so the type has no null

    By default a control's type is T | null because reset() sets it to null. NonNullableFormBuilder (inject(FormBuilder).nonNullable) applies this to every control.

  40. 40. What does implementing ControlValueAccessor allow?

    Correct answer: A custom component works with formControlName like an input

    Implement writeValue, registerOnChange, registerOnTouched (and optionally setDisabledState) and provide NG_VALUE_ACCESSOR. The forms API then talks to your component through these methods.

  41. 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/contentChildren query projected content instead of the component's own view.

  42. 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 select attribute 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 @if in the child.

  43. 43. What does this @defer block do?

    @defer (on viewport) {
      <app-comments />
    } @placeholder {
      <p>Comments</p>
    }

    Correct answer: Loads app-comments only when the placeholder enters the viewport

    The deferred component's code goes into a separate chunk. Other triggers are on idle (default), on interaction, on hover, on timer(2s) and when condition; prefetch on ... downloads earlier.

  44. 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: false is needed when the output depends on internal mutations (like async), but it is costly when the work is heavy.

  45. 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 host property in the decorator metadata

    The Angular style guide prefers the host object over the @HostBinding/@HostListener decorators: everything about the host is in one place and the expressions are type-checked.

  46. 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 />). afterNextRender runs only in the browser after rendering, so the code is safe with SSR.

  47. 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

    HttpRequest is immutable, so interceptors call clone. Interceptors run in the order they are listed and can also handle errors, retries, logging and caching.

  48. 48. How do you test a service that uses HttpClient without real network calls?

    Correct answer: Use provideHttpClientTesting() and HttpTestingController

    httpTesting.expectOne('/api/users').flush([...]) returns a fake response, and verify() in afterEach ensures no unexpected requests were made.

  49. 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() (or await fixture.whenStable()), then query elements via fixture.nativeElement or debugElement.

  50. 50. When migrating to standalone, how do you keep using an NgModule-based library?

    Correct answer: Add the NgModule to the component's imports

    Standalone and NgModule code interoperate. The CLI also has a schematic (ng generate @angular/core:standalone) that migrates an existing project step by step.

  51. 51. How does forkJoin differ from combineLatest?

    Correct answer: forkJoin emits once when all complete, combineLatest on every emission

    forkJoin fits parallel HTTP requests. combineLatest fits long-lived streams like filters plus data; with signals, computed often replaces it.

  52. 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 (or lastValueFrom) from RxJS

    toPromise() is deprecated. firstValueFrom resolves on the first value and unsubscribes; it rejects if the stream completes without values.

  53. 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 retry operator with count and delay

    Retry only idempotent requests (like GET). delay can be a function for exponential backoff.

  54. 54. How does ReplaySubject(3) differ from BehaviorSubject?

    Correct answer: It replays the last 3 values and needs no initial value

    BehaviorSubject always has a current value (one) and requires an initial value. ReplaySubject buffers a configurable number of values.

  55. 55. What does the scan operator do?

    clicks$.pipe(scan((total) => total + 1, 0))

    Correct answer: Accumulates state and emits each intermediate result

    reduce waits for completion; scan emits after every value, which suits counters or a reducer-like state stream.

  56. 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 HttpContext token and check it in the interceptor

    The interceptor reads req.context.get(SKIP_AUTH) and forwards the request unchanged. It's cleaner than matching URLs.

  57. 57. What does provideHttpClient(withFetch()) change?

    Correct answer: HttpClient uses the Fetch API instead of XMLHttpRequest

    The API of HttpClient stays the same. Fetch works natively in Node.js, which is why it's preferred on the server.

  58. 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> plus ngTemplateOutlet

    A template can also be passed as an input to a child, which lets the parent customize how items are rendered.

  59. 59. What does hostDirectives in 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. 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 updated

    These callbacks don't run during SSR, which makes them a safe place for browser-only DOM work.

  61. 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 DestroyRef and call onDestroy

    DestroyRef belongs to the current injector: a component, a route's environment, or the app. takeUntilDestroyed is built on it.

  62. 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. 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 loadChildren that imports a routes array

    The whole feature (components, services from route providers) goes into a separate chunk loaded on first visit.

  64. 64. How do you animate transitions between routes with the browser's View Transitions API?

    provideRouter(routes, withViewTransitions())

    Correct answer: Enable withViewTransitions() in provideRouter

    Browsers without View Transitions support navigate as usual. The ::view-transition-* pseudo-elements control the animation.

  65. 65. What does redirectTo as 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. 66. How do you give an InjectionToken a default value without adding providers?

    export const PAGE_SIZE = new InjectionToken<number>('PAGE_SIZE', {
      providedIn: 'root',
      factory: () => 20,
    });

    Correct answer: The factory option with providedIn: 'root'

    The factory can call inject() for other dependencies. Any provider for the token still overrides the default.

  67. 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.createComponent and ComponentRef.setInput

    setInput works with signal inputs and marks OnPush components for check. NgComponentOutlet covers simple template cases.

  68. 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. 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(), then detectChanges()

    Signal inputs are read-only from the class, and setInput goes through the same path as a parent binding, including OnPush marking.

  70. 70. What does toSignal(obs$, { initialValue: [] }) change compared to toSignal(obs$)?

    Correct answer: It starts with [], so the type has no undefined

    For Observables that emit synchronously (like a BehaviorSubject), requireSync: true removes undefined without an initial value.

  71. 71. What is a rxResource (or resource) useful for compared to manual subscribe in effect?

    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 effect and flags is error-prone.

  72. 72. Why avoid subscribe inside 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. 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. 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 TemplateRef input and use ngTemplateOutlet

    <ng-content> projects content once; a template can be stamped out many times with a different context for each item.

  75. 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

    track helps reuse DOM nodes but doesn't reduce their number. Virtual scrolling keeps the DOM small; pagination is another option.