← Interview prep

Angular interview questions

Components, RxJS, change detection, and Angular interview staples.

195 questions · Page 7 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 7 of 10

Questions 121–140 of 195 · 0 of 20 on this page marked learned

121.angular-0121Mediummid

What is DestroyRef, and how does it improve cleanup compared with ngOnDestroy?

DestroyRef is an injectable that lets any code register a callback to run when its context (component, directive, service or injector) is destroyed. It allows cleanup to be written next to the setup, in functions and utilities, without a class implementing ngOnDestroy.

Full answer

Before Angular 16, cleanup needed a class with ngOnDestroy. That forced setup code and teardown code to live in two places, and a reusable function could not clean up after itself.

DestroyRef solves this. You inject it, and call onDestroy(callback). The callback runs when the owner is destroyed. The method returns a function that unregisters the callback if you need to cancel it earlier.

What can provide a DestroyRef:

  • A component or directive: destroyed when the view is removed.
  • A service: destroyed with its injector (root services when the app is destroyed, component-level services with the component).
  • An environment injector, such as a route's injector.

Why it is better:

  1. Colocation: register the listener and its removal in the same function.
  2. Reusable helpers: a function like onWindowResize(callback) can inject DestroyRef and clean up on its own. Any component that calls it gets cleanup for free.
  3. Works in plain functions called from an injection context, without a base class.
  4. It powers takeUntilDestroyed(), toSignal, effects, and afterNextRender.

Rules:

  • inject(DestroyRef) needs an injection context (constructor, field initialiser, factory). Pass the ref along if you call a helper later, for example from an event handler.
  • If you need to know in a callback whether the owner is already destroyed, check destroyRef.destroyed (available in recent versions).
  • The order in which several callbacks run is not part of the documented behaviour, so do not depend on it.
  • ngOnDestroy still works. It is fine for classes that already use it, and you can mix both.

Use it for event listeners, intervals, observers (ResizeObserver, IntersectionObserver), WebSocket connections, and any manual subscription.

typescript
import { Component, DestroyRef, inject, signal } from '@angular/core';

export const listeners = { active: 0 };

// A reusable helper: setup and cleanup in one place, no class needed.
export function onWindowResize(callback: (width: number) => void): void {
  const destroyRef = inject(DestroyRef);
  const handler = () => callback(window.innerWidth);
  window.addEventListener('resize', handler);
  listeners.active++;

  destroyRef.onDestroy(() => {
    window.removeEventListener('resize', handler);
    listeners.active--;
  });
}

@Component({
  selector: 'app-width',
  template: `Width: {{ width() }}`,
})
export class WidthComponent {
  readonly width = signal(window.innerWidth);

  constructor() {
    onWindowResize((w) => this.width.set(w));
  }
}

Angular 20.3, type-checked. A Karma test checks that the resize listener is removed when the component is destroyed.

Key points

  • `DestroyRef.onDestroy(cb)` runs `cb` when the owner is destroyed. It returns an unregister function.
  • Works for components, directives, services and injectors.
  • Enables reusable cleanup helpers and powers `takeUntilDestroyed`.
  • Needs an injection context to inject. Do not rely on callback order.

Common mistakes

  • Calling `inject(DestroyRef)` inside an event handler, outside an injection context.
  • Registering a callback and forgetting that it may run after the work is already finished.
  • Depending on the order of several callbacks.

Follow-ups

  • How does `takeUntilDestroyed` use `DestroyRef`?
  • What is destroyed when a route is left?
  • How would you write a helper that listens to window resize?

Tips

  • Show a helper function that cleans itself up. It is the real benefit.
  • Mention the unregister function.
  • Say that `ngOnDestroy` still works.

Evaluation rubric

  • Explains what DestroyRef is and who provides it.
  • Gives benefits over ngOnDestroy.
  • Mentions injection context rules.
122.angular-0122Mediummid

What are afterNextRender and afterEveryRender, what are the phases, and when should you use them instead of lifecycle hooks?

afterNextRender runs a callback once after the next time Angular has finished rendering, and afterEveryRender runs after every render. They run only in the browser, never during server rendering, so they are the safe place for DOM measurements and third party libraries. Phases (earlyRead, write, mixedReadWrite, read) order reads and writes to avoid layout thrashing.

Full answer

Some work needs the real DOM: measuring an element, focusing an input, starting a chart library, or reading window. During server rendering there is no browser DOM, and in the browser the DOM is only correct after Angular has finished updating it.

afterNextRender(callback, options?) registers a callback that runs once, after the next completed render of the application. afterEveryRender(callback) runs after every render (it was called afterRender before Angular 20). Both:

  • Must be called in an injection context (a constructor or field initialiser), or pass an injector.
  • Run only in the browser. They are skipped on the server, so you do not need isPlatformBrowser checks.
  • Run after change detection finished, so the DOM is up to date.
  • Are cleaned up automatically with the component.

Phases. If several components read and write the DOM in separate callbacks, they can force the browser to recalculate layout again and again (layout thrashing). To avoid this, pass an object with phases. Angular runs all callbacks of one phase before moving to the next:

  1. earlyRead: read the DOM before writes (rarely needed).
  2. write: change the DOM (styles, classes, sizes).
  3. mixedReadWrite: the default when you pass a plain function. It may do both. Prefer the other phases.
  4. read: read the DOM after writes, for example getBoundingClientRect.

Each phase function can return a value that is passed to the next phase.

Versus lifecycle hooks: ngAfterViewInit also runs on the server and runs only for that component's view. A render hook runs after the whole application tree is stable, and not on the server. Use afterNextRender for browser-only DOM work, and ngAfterViewInit when you only need the component's own view. Do not set signals in a render hook without a plan: updating state triggers another render, and with afterEveryRender this can loop.

typescript
import { Component, ElementRef, afterNextRender, inject, signal } from '@angular/core';

export const order: string[] = [];

@Component({
  selector: 'app-measure-box',
  template: `<div class="box">Content</div><p>Height: {{ height() }}</p>`,
})
export class MeasureBoxComponent {
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  readonly height = signal(0);

  constructor() {
    afterNextRender({
      write: () => {
        order.push('write');
        const box = this.host.nativeElement.querySelector('.box') as HTMLElement;
        box.style.height = '80px';
        return box; // passed to the next phase
      },
      read: (box) => {
        order.push('read');
        this.height.set(box.getBoundingClientRect().height);
      },
    });
  }
}

Angular 20.3, strict template check passes. A Karma test checks that the phase callbacks run in write then read order and that the size is read after the write.

Key points

  • `afterNextRender` runs once, `afterEveryRender` runs on every render, both browser only.
  • They run after the whole app has rendered, so DOM measurements are correct.
  • Phases (`earlyRead`, `write`, `mixedReadWrite`, `read`) prevent layout thrashing.
  • Use them for third party DOM libraries, focus and measurement. Avoid state changes that cause endless renders.

Common mistakes

  • Using `window` in a constructor and breaking server rendering.
  • Reading and writing the DOM in one callback in a loop, causing layout thrashing.
  • Setting a signal in `afterEveryRender` and creating a render loop.

Follow-ups

  • Why do render hooks not run on the server?
  • How do phases pass values to each other?
  • When would `ngAfterViewInit` still be the right hook?

Tips

  • Name the browser-only property first. It is the main reason.
  • Explain layout thrashing in one sentence.
  • Say that `afterRender` was renamed `afterEveryRender`.

Evaluation rubric

  • Explains when the hooks run and where.
  • Knows the phases and why they exist.
  • Compares correctly with lifecycle hooks.
123.angular-0123Mediummid

What is a multi provider in Angular, and how do you use it to build a plugin style extension point?

A provider with multi true adds its value to an array instead of replacing earlier values, so several parts of the app can contribute to one token. Injecting the token gives the array. Angular uses this for validators and interceptors, and you can use it for plugins, validators or menu items.

Full answer

Normally, when two providers use the same token, the last one wins. With multi: true, each provider adds one entry to an array, and the injector returns all entries together.

Pattern:

  1. Create a token for one item: new InjectionToken<MenuItem>('MENU_ITEM').
  2. Different features add providers: { provide: MENU_ITEM, useValue: {...}, multi: true }.
  3. A consumer injects inject(MENU_ITEM) and receives MenuItem[]. If nobody provided one, it fails, so give a default factory that returns an empty array, or use { optional: true }.

Typical uses:

  • Plugins and feature registration: each feature library registers its menu entry, route links, or search provider, without the shell knowing them.
  • Validation rules, formatters, or exporters that can be extended.
  • Angular itself: NG_VALIDATORS, NG_ASYNC_VALIDATORS, NG_VALUE_ACCESSOR, APP_INITIALIZER, and (in the classic API) HTTP_INTERCEPTORS.

Details that matter:

  • Order: entries are in the order the providers were registered, so that merging configs with mergeApplicationConfig can change the order. Do not depend on order unless you sort, for example with a priority field.
  • All providers for the same token must use multi: true. Mixing a multi and a non-multi provider for one token causes an error or surprising results.
  • The scope matters. Providers at different injector levels do not merge: a child injector's multi providers replace the parent's array for that subtree, not add to it.
  • Wrap registration in a helper function that returns Provider or EnvironmentProviders, such as provideMenuItem(item), so callers do not repeat multi: true.

Compared with a service that has a register() method, multi providers need no start-up ordering: all contributions exist when the injector is created.

typescript
import { InjectionToken, Provider, inject } from '@angular/core';

export interface MenuItem {
  label: string;
  path: string;
  priority: number;
}

export const MENU_ITEMS = new InjectionToken<MenuItem[]>('MENU_ITEMS', {
  factory: () => [],
});

export function provideMenuItem(item: MenuItem): Provider {
  return { provide: MENU_ITEMS, useValue: item, multi: true };
}

export function sortedMenu(): MenuItem[] {
  return [...inject(MENU_ITEMS)].sort((a, b) => a.priority - b.priority);
}

// In a feature: providers: [provideMenuItem({ label: 'Marks', path: '/marks', priority: 2 })]
// In another:   providers: [provideMenuItem({ label: 'Home', path: '/', priority: 1 })]

Angular 20.3, type-checked. A Karma test checks that two multi providers give an array in registration order and that the sorted helper orders it by priority.

Key points

  • `multi: true` collects provider values into an array under one token.
  • Use it for plugin points, and wrap it in a `provide...` helper.
  • All providers for the token must be multi. Order follows registration. Child injectors do not merge with parents.
  • Angular uses it for validators, value accessors and initialisers.

Common mistakes

  • Forgetting `multi: true` on one provider, so it replaces the others.
  • Depending on the order of the array.
  • Expecting a child injector to add to the parent's array.

Follow-ups

  • How would you add a priority to plugin entries?
  • What does a token with a `factory` default give you?
  • Why is `NG_VALUE_ACCESSOR` a multi provider?

Tips

  • Use the menu items example. It is clear and realistic.
  • Say that child injectors replace, not extend.
  • Mention the `provide...` helper function style.

Evaluation rubric

  • Explains multi providers and the resulting array.
  • Gives a plugin example and Angular's own uses.
  • Knows the scope and order caveats.
124.angular-0124Mediummid

What do the optional, self, skipSelf and host options of inject() do, and when do you need them?

By default, inject looks up the injector tree and throws if it finds nothing. optional returns null instead of throwing, self searches only the current injector, skipSelf starts at the parent, and host stops the search at the host component. They give precise control in nested components and directives.

Full answer

Angular looks for a provider in the element injector of the current component, then up through parent elements, then in the environment injectors (route, root, platform). The inject(Token, options) flags change this search.

  • optional: true: if no provider is found, return null instead of throwing NullInjectorError. Use it for dependencies that may not exist, such as a parent component or an optional configuration.
  • self: true: look only in the current element's injector (the component or directive itself). If it is not provided there, fail (or return null with optional). Use it to require that a directive has its own provider.
  • skipSelf: true: start looking at the parent injector. Use it when a service wants to find another instance of itself above it, for example a nested tree node that needs its parent node's service.
  • host: true: stop the search at the host element of the current component's template. Content projected from outside is not searched beyond the host. It is useful for directives that must only link to a provider inside the same component, and it is common in form controls.

Older constructor style used decorators with the same names: @Optional(), @Self(), @SkipSelf(), @Host(). The inject options replace them with a more flexible and type-safe syntax. With optional: true the return type becomes T | null.

Common cases:

  1. Recursive components: each tree node provides a NodeService. Inside, inject(NodeService, { skipSelf: true, optional: true }) finds the parent node's service, and the root node gets null.
  2. Optional features: inject(LoggerService, { optional: true }) so a library works without a logger.
  3. Preventing accidental sharing: { self: true } makes the directive fail loudly if it was not given its own state.

Combine flags: { self: true, optional: true } means "only mine, and null if absent".

typescript
import { Component, Injectable, inject, input } from '@angular/core';

@Injectable()
export class NodeService {
  // Finds the parent node's service. The root node gets null.
  readonly parent = inject(NodeService, { skipSelf: true, optional: true });

  get depth(): number {
    return this.parent ? this.parent.depth + 1 : 0;
  }
}

@Component({
  selector: 'app-tree-node',
  providers: [NodeService], // each node has its own service
  template: `
    <div>{{ name() }} (depth {{ service.depth }}, parent {{ service.parent ? 'yes' : 'none' }})</div>
    <ng-content />
  `,
})
export class TreeNodeComponent {
  readonly name = input.required<string>();
  protected readonly service = inject(NodeService, { self: true });
}

@Component({
  selector: 'app-tree',
  imports: [TreeNodeComponent],
  template: `
    <app-tree-node name="root">
      <app-tree-node name="child">
        <app-tree-node name="grandchild" />
      </app-tree-node>
    </app-tree-node>
  `,
})
export class TreeComponent {}

Angular 20.3, strict template check passes. A Karma test builds a three level tree and checks the depth and the parent of each node.

Key points

  • `optional` returns null instead of throwing. `self` limits to the current injector.
  • `skipSelf` starts from the parent. `host` stops at the host component.
  • Recursive components use `skipSelf` and `optional` to find their parent.
  • The `inject` options replace the old decorators.

Common mistakes

  • Forgetting `optional` and getting `NullInjectorError` for an optional dependency.
  • Using `skipSelf` at the root, where no parent exists, without `optional`.
  • Assuming flags apply to environment injectors as they do to element injectors.

Follow-ups

  • How would a tree node find the root of the tree?
  • What does the injector search order look like for a directive on a component?
  • How do `viewProviders` interact with `host`?

Tips

  • Use the recursive tree example. It shows skipSelf and optional together.
  • Mention the return type becomes nullable.
  • Give the old decorator names so you can read legacy code.

Evaluation rubric

  • Explains each flag correctly.
  • Gives at least one realistic example.
  • Knows the legacy decorator equivalents.
125.angular-0125Mediummid

What is forwardRef in Angular, when do you need it, and how do you solve circular dependencies properly?

forwardRef lets you refer to a class that is declared later in the file, because classes are not available before their declaration runs. It is needed in decorator metadata such as NG_VALUE_ACCESSOR providers. A real circular dependency between services, where A needs B and B needs A, should be removed by redesigning, not hidden.

Full answer

In JavaScript, a class declaration is not usable before the line where it is declared (it is in the "temporal dead zone"). Decorators are evaluated when the class is defined, so this fails:

@Component({ providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: MyInput, multi: true }] }) export class MyInput { }

When the decorator runs, MyInput is not yet initialised, so the reference throws or is undefined. forwardRef(() => MyInput) delays the lookup: it stores an arrow function and Angular calls it later, when the class exists. This is why every custom form control needs useExisting: forwardRef(() => MyInput).

You also meet it with imports: [forwardRef(() => OtherComponent)] when two standalone components reference each other (a recursive tree of components, where a node component contains itself, does not need it because a component can refer to itself in its own template).

A different problem is a true circular dependency of services: AuthService injects UserService, and UserService injects AuthService. Angular can not create one before the other and throws NG0200: Circular dependency in DI detected. forwardRef does not fix this. Options, from best to worst:

  1. Redesign: extract the shared part into a third service (SessionStore) that both depend on. This is the real fix and usually shows a missing concept.
  2. Replace one direction with events or a stream: the second service emits, the first subscribes.
  3. Inject lazily: inject(Injector) and call injector.get(UserService) when needed (after both exist). This works but hides the dependency, so use it sparingly.

Also watch for circular file imports (A imports B and B imports A at the top). Bundlers may produce undefined at start-up. Tools such as madge or the lint rule import/no-cycle detect them.

typescript
import { Component, Injectable, forwardRef, inject } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

// 1. forwardRef is needed because the class is referenced inside its own decorator.
@Component({
  selector: 'app-rating',
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => RatingComponent), multi: true }],
  template: `Rating`,
})
export class RatingComponent implements ControlValueAccessor {
  writeValue(): void {}
  registerOnChange(): void {}
  registerOnTouched(): void {}
}

// 2. A real circular dependency. forwardRef does not help here.
@Injectable({ providedIn: 'root' })
export class AuthService {
  readonly users = inject(UserService);
}

@Injectable({ providedIn: 'root' })
export class UserService {
  readonly auth = inject(AuthService);
}

// Fix: both depend on a third service that owns the shared state.
@Injectable({ providedIn: 'root' })
export class SessionStore {
  userName: string | null = null;
}

@Injectable({ providedIn: 'root' })
export class FixedAuthService {
  readonly session = inject(SessionStore);
}

@Injectable({ providedIn: 'root' })
export class FixedUserService {
  readonly session = inject(SessionStore);
}

Angular 20.3, type-checked. A Karma test creates the injector with two services that need each other and confirms that the error is NG0200. The input component with forwardRef is the fixed form shown below.

Key points

  • `forwardRef` delays a class reference until the class is initialised, for decorator metadata.
  • Custom form controls use it in `NG_VALUE_ACCESSOR` providers.
  • It does not fix circular service dependencies (NG0200). Redesign them.
  • Detect circular imports with lint or tooling.

Common mistakes

  • Using `forwardRef` to hide a real circular service dependency.
  • Writing `useExisting: MyInput` without `forwardRef` in the class's own decorator.
  • Ignoring circular file imports until a mysterious `undefined` appears.

Follow-ups

  • Why are decorators evaluated before the class is ready?
  • How would you break the Auth and User service cycle?
  • What does `NG0200` tell you?

Tips

  • Explain the temporal dead zone in one sentence.
  • Separate "reference order" from "circular dependency".
  • Offer the third service solution first.

Evaluation rubric

  • Explains why forwardRef exists.
  • Distinguishes it from circular dependency errors.
  • Gives sound design solutions.
126.angular-0126Mediummid

What are RxJS schedulers, and how do asapScheduler, asyncScheduler, observeOn and subscribeOn change when values are delivered?

A scheduler controls when and on which task a value is delivered. Synchronous delivery is the default, asapScheduler uses a microtask, asyncScheduler uses setTimeout (a macrotask), and animationFrameScheduler uses the next frame. observeOn changes when values are delivered to the subscriber, and subscribeOn changes when the subscription starts.

Full answer

RxJS observables are synchronous unless an operator introduces time. of(1, 2, 3) emits all values immediately during subscribe. A scheduler lets you choose when work happens relative to the browser event loop.

Main schedulers:

  • queueScheduler: synchronous, but orders nested work in a queue (rarely needed).
  • asapScheduler: schedules work in a microtask (like a Promise callback). It runs after the current code finishes, before timers and before rendering.
  • asyncScheduler: uses setTimeout or setInterval (macrotask). Used internally by delay, timer, interval, and debounceTime.
  • animationFrameScheduler: uses requestAnimationFrame, good for animation-like updates.

Operators that use them:

  • observeOn(scheduler): re-emits each value on the given scheduler. It affects delivery to the subscriber. Use it to move expensive subscriber work off the current call stack, or to batch to the next frame.
  • subscribeOn(scheduler): delays the subscription itself.
  • Time operators accept a scheduler as the last argument, which is also how marble tests use virtual time (TestScheduler).

Order of execution in one run: synchronous code first, then microtasks (asap), then macrotasks (async). Example: subscribing with synchronous, asap and async delivery prints "sync", then "asap", then "async", regardless of the order you wrote them.

Practical uses: observeOn(animationFrameScheduler) to avoid updating the DOM more than once per frame; observeOn(asapScheduler) to avoid re-entrancy bugs, where a handler triggers another emission in the middle of the current one; and asyncScheduler in tests with fake timers.

With Angular, schedulers interact with zones and change detection: an asyncScheduler timer is a zone-patched setTimeout and can trigger change detection, and in zoneless apps the update still needs a signal or markForCheck.

typescript
import { asapScheduler, asyncScheduler, observeOn, of } from 'rxjs';

console.log('start');

of('sync').subscribe((v) => console.log(v));
of('asap').pipe(observeOn(asapScheduler)).subscribe((v) => console.log(v));
of('async').pipe(observeOn(asyncScheduler)).subscribe((v) => console.log(v));

Promise.resolve().then(() => console.log('promise microtask'));
console.log('end');

RxJS 7.8. The script was run in Node 24 twice with identical output, which shows sync first, then asap, then async.

Key points

  • Default delivery is synchronous. Schedulers choose microtask, macrotask or animation frame.
  • `observeOn` changes delivery to the subscriber. `subscribeOn` changes when subscription starts.
  • Order: synchronous, then asap (microtask), then async (macrotask).
  • Use `animationFrameScheduler` to limit DOM updates to once per frame.

Common mistakes

  • Assuming `of(...)` is asynchronous.
  • Using `observeOn(asyncScheduler)` and being surprised when ordering changes.
  • Forgetting that timers in the zone can trigger change detection.

Follow-ups

  • How does `TestScheduler` use virtual time?
  • Why does `asapScheduler` run before `asyncScheduler`?
  • What does `debounceTime` use by default?

Tips

  • Show the execution order example.
  • Name the event loop terms microtask and macrotask correctly.
  • Link to tests with virtual time.

Evaluation rubric

  • Names the schedulers and what each uses.
  • Explains observeOn and subscribeOn.
  • Predicts the order of output.
127.angular-0127Mediummid

What causes memory leaks with RxJS in Angular apps, and how does shareReplay without refCount leak?

A leak happens when a long-lived source keeps a subscription that holds a destroyed component. shareReplay without refCount keeps its source subscribed forever after the first subscriber, so an infinite source (interval, WebSocket) never stops. Use shareReplay with refCount true, takeUntilDestroyed, async pipe and toSignal.

Full answer

RxJS leaks follow one rule: a source holds a reference to every subscriber's callback. If the source lives longer than the subscriber and never completes, the callback (and the component it references) stays alive.

Common causes:

  1. Subscribing to a root service Subject, interval, fromEvent(window), or store stream in a component and not unsubscribing.
  2. Forgetting to unsubscribe in nested subscriptions, so inner subscriptions pile up (use flattening operators).
  3. shareReplay without refCount. shareReplay(1) means refCount: false, and it still does in RxJS 7.8 for backward compatibility: once started, it never unsubscribes from its source. So with a source like interval(1000) or a WebSocket, the source keeps running after the last subscriber leaves. Even if the first subscriber was a component that is now destroyed, the timer continues forever.
  4. Event listeners added with addEventListener and not removed.
  5. Keeping large values in ReplaySubject with a large bufferSize or no time window.

Fixes:

  • shareReplay({ bufferSize: 1, refCount: true }): when the subscriber count drops to zero, the source is unsubscribed, and a later subscriber restarts it. This is usually what you want for page-level data. For app-level caches that should live for the whole session (user profile), refCount: false is deliberate, so document it.
  • takeUntilDestroyed() last in the pipe, async pipe, toSignal.
  • take(1), first() or takeUntil(stop$) for finite use.
  • A Subscription container and unsubscribe() for old code.

Finding leaks: use the browser Memory tab, take heap snapshots before and after navigating away and back, and look for detached DOM nodes and component instances that are still reachable. A simple check: add a teardown log inside a custom Observable and watch whether it runs when the component closes.

typescript
import { Observable, shareReplay } from 'rxjs';

function makeSource(name: string): Observable<number> {
  return new Observable<number>((subscriber) => {
    const id = setInterval(() => subscriber.next(1), 5);
    console.log(name, 'source started');
    return () => {
      clearInterval(id);
      console.log(name, 'source torn down');
    };
  });
}

const leaky$ = makeSource('shareReplay(1)').pipe(shareReplay(1));
const safe$ = makeSource('refCount true').pipe(shareReplay({ bufferSize: 1, refCount: true }));

const a = leaky$.subscribe();
const b = safe$.subscribe();

setTimeout(() => {
  a.unsubscribe();
  b.unsubscribe();
  setTimeout(() => {
    console.log('after the last unsubscribe, only the refCount source is torn down');
    process.exit(0);
  }, 20);
}, 20);

RxJS 7.8. The script was run in Node 24 twice with identical output. It counts source teardowns with and without refCount.

Key points

  • Leaks come from long-lived sources keeping subscriber callbacks alive.
  • `shareReplay(1)` does not unsubscribe from the source. Use `{ bufferSize: 1, refCount: true }`.
  • Prefer `async`, `toSignal`, `takeUntilDestroyed`.
  • Find leaks with heap snapshots and teardown logs.

Common mistakes

  • Using `shareReplay(1)` on an infinite source in a component-level stream.
  • Using `refCount: true` for a cache that must survive route changes, losing the data.
  • Nested subscribes that never clean up.

Follow-ups

  • When is `refCount: false` the right choice?
  • How would you write a test that proves the source was unsubscribed?
  • What is the difference between `share` and `shareReplay`?

Tips

  • Show the `shareReplay` teardown demo. It proves the point.
  • Mention that `refCount: false` can be deliberate.
  • Describe how you find leaks with the profiler.

Evaluation rubric

  • Explains the root cause of RxJS leaks.
  • Identifies the shareReplay refCount issue.
  • Gives fixes and a way to detect leaks.
128.angular-0128Mediummid

What is a RouteReuseStrategy, and how would you write one that keeps the state of a list page when the user goes to a detail page and back?

By default the router destroys a component when you navigate away and creates a new one when you come back. A custom RouteReuseStrategy can detach the component tree for chosen routes and store it, then attach it again when the user returns, which preserves scroll position and filters. You choose the routes with route data.

Full answer

The router asks a RouteReuseStrategy five questions during every navigation:

  1. shouldReuseRoute(future, current): should the current component be reused for the new route? The default returns true only when the route config is the same.
  2. shouldDetach(route): when leaving a route, should its component tree be stored instead of destroyed?
  3. store(route, handle): store the detached tree.
  4. shouldAttach(route): when entering a route, do we have a stored tree?
  5. retrieve(route): return the stored tree to attach.

Implementation for a list page:

  • Mark routes with data: { reuse: true }.
  • shouldDetach returns true for those routes.
  • store saves the handle in a Map using a key, the route path (or route.routeConfig.path).
  • shouldAttach returns true if the map has the key.
  • retrieve returns the saved handle.
  • shouldReuseRoute keeps the default: future.routeConfig === curr.routeConfig.

Provide it with { provide: RouteReuseStrategy, useClass: AppReuseStrategy }.

Cautions:

  • A detached component is not destroyed. Its subscriptions and timers keep running and its memory stays. Pause work in the component using the router (there are no "deactivate" lifecycle hooks, so listen to router events or use ngOnDestroy carefully: it is not called on detach).
  • Stale data. A stored list shows old data on return. Refresh on NavigationEnd when the route is reattached, or set a time limit for stored entries.
  • Clear the store on logout. Otherwise the next user could see the previous user's data. This is also a privacy problem.
  • Parameterised routes need a key that includes the params if each should be cached separately, and a cap on how many to keep.
  • A simpler alternative for many cases is to keep the filters in the URL query params and the data in a cache service. This survives refresh and is easier to reason about.
typescript
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';

export class AppReuseStrategy implements RouteReuseStrategy {
  private readonly stored = new Map<string, DetachedRouteHandle>();

  private key(route: ActivatedRouteSnapshot): string {
    return route.routeConfig?.path ?? '';
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === current.routeConfig;
  }

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data['reuse'] === true;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
    if (handle) {
      this.stored.set(this.key(route), handle);
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return route.data['reuse'] === true && this.stored.has(this.key(route));
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return this.stored.get(this.key(route)) ?? null;
  }

  clear(): void {
    this.stored.clear(); // call on logout
  }
}

// providers: [{ provide: RouteReuseStrategy, useClass: AppReuseStrategy }]
// routes:    { path: 'students', component: StudentListComponent, data: { reuse: true } }

Angular 20.3, type-checked. The strategy is compiled against the router types, but it was not run in a Karma test here.

Key points

  • `RouteReuseStrategy` has five methods: reuse, detach, store, attach, retrieve.
  • Mark cacheable routes with `data`, store handles in a map, and provide the strategy with DI.
  • Detached components stay alive, so pause work, refresh stale data, and clear on logout.
  • Often URL params plus a cache service are simpler.

Common mistakes

  • Expecting `ngOnDestroy` to run when a component is detached.
  • Caching without clearing the store on logout.
  • Caching routes with parameters under one key.

Follow-ups

  • How would you limit the cache to five entries?
  • How do you refresh data when a cached page is shown again?
  • When would URL state be better than caching components?

Tips

  • List the five methods in order of use.
  • Mention privacy and stale data. Those are the real risks.
  • Offer the URL state alternative.

Evaluation rubric

  • Knows the strategy methods and their roles.
  • Writes a working cache for chosen routes.
  • Lists the risks and alternatives.
129.angular-0129Mediummid

What happens, step by step, when a user navigates to a URL in the Angular router, and in what order do guards and resolvers run?

The router parses the URL, matches routes (running canMatch), redirects, then runs canDeactivate on the routes being left, then canActivateChild and canActivate from parent to child, then resolvers, and finally activates the components. Any guard that returns false or a UrlTree cancels the navigation.

Full answer

A navigation is a pipeline of steps. Knowing the order helps you place logic in the right guard.

  1. Trigger: routerLink, router.navigate, or a URL change. The router emits NavigationStart.
  2. Recognition: the URL is parsed into a tree and matched against the route config. During matching, canMatch guards run for each candidate route. A false result means "this route does not match", and the router tries the next route. This is also where redirects (redirectTo) apply, and lazy loadChildren or loadComponent bundles load.
  3. canDeactivate guards of the components being left run, starting from the deepest (they can warn about unsaved changes).
  4. canActivateChild of parents, and canActivate of each route being entered, run from the top route down to the child. If any returns false, the navigation is cancelled. If any returns a UrlTree, the router cancels and redirects.
  5. Resolvers run (in parallel for sibling routes) and their results are stored in route.data. If a resolver errors, the navigation fails (NavigationError) unless you handle it.
  6. canLoad is the older name of the check before loading a lazy module (replaced by canMatch).
  7. Activation: components are created or reused, router-outlets display them, and titles are set. The router emits NavigationEnd, and Scroll events follow.

Events you can watch: NavigationStart, RoutesRecognized, GuardsCheckStart, GuardsCheckEnd, ResolveStart, ResolveEnd, NavigationEnd, NavigationCancel, NavigationError.

Guideline for placement:

  • Choose the route based on a condition (feature flag, role): canMatch.
  • Block or redirect based on authentication: canActivate.
  • Prevent losing edits: canDeactivate.
  • Load data the page cannot render without: resolver (or load in the component with a loading state, which is often a better experience).

If a newer navigation starts while one is running, the older one is cancelled (NavigationCancel), so guards and resolvers should return observables that are safe to unsubscribe.

typescript
import { inject } from '@angular/core';
import { CanActivateFn, CanDeactivateFn, CanMatchFn, ResolveFn, Routes } from '@angular/router';
import { Component } from '@angular/core';

export const order: string[] = [];

const canMatch: CanMatchFn = () => (order.push('canMatch'), true);
const canActivate: CanActivateFn = () => (order.push('canActivate'), true);
const resolve: ResolveFn<string> = () => (order.push('resolve'), 'data');

@Component({ selector: 'app-page-a', template: `A` })
export class PageAComponent {}

@Component({ selector: 'app-page-b', template: `B` })
export class PageBComponent {}

export const canLeave: CanDeactivateFn<PageAComponent> = () => (order.push('canDeactivate'), true);

export const routes: Routes = [
  { path: 'a', component: PageAComponent, canDeactivate: [canLeave] },
  { path: 'b', component: PageBComponent, canMatch: [canMatch], canActivate: [canActivate], resolve: { data: resolve } },
];

// Navigating from /a to /b records (captured order, see the notes):
//   canMatch, canDeactivate, canActivate, resolve   (captured in Karma, Angular 20.3)

Angular 20.3, type-checked. The order in the comment below was captured from a Karma run in headless Chrome with logging guards and a resolver.

Key points

  • Order: recognise and match (`canMatch`), `canDeactivate`, `canActivateChild`/`canActivate` top down, resolvers, activation.
  • A `false` result cancels navigation. A `UrlTree` redirects.
  • Events mark each stage and can drive loading indicators.
  • A new navigation cancels the previous one.

Common mistakes

  • Putting role-based route selection in `canActivate` when `canMatch` fits and avoids loading the code.
  • Doing slow work in a resolver and blocking navigation with no feedback.
  • Not handling resolver errors.

Follow-ups

  • Why is `canMatch` better than `canActivate` for feature flags?
  • Do resolvers for parent and child routes run in sequence or in parallel?
  • How do you prevent a user from leaving a dirty form?

Tips

  • Walk through the stages in order. Interviewers expect the sequence.
  • Name the events for each stage.
  • Give one example guard for each type.

Evaluation rubric

  • Gets the order of the stages right.
  • Knows which guard fits which problem.
  • Understands cancellation.
130.angular-0130Mediummid

How do you write an async validator that checks with the server whether a username is free, without sending a request on every keystroke?

An async validator returns an Observable or Promise of errors or null. Use timer with switchMap inside it to debounce and cancel earlier checks, handle errors so the field does not stay pending, run it only after sync validators pass, and show the pending state to the user. updateOn blur is another way to reduce requests.

Full answer

An AsyncValidatorFn receives the control and returns Observable<ValidationErrors | null> (or a Promise). Angular runs async validators only when all sync validators pass, and while one is running the control status is PENDING.

Problem: Angular calls the validator on every value change, and each call would send a request. Also, an old slow response could arrive after a newer one.

Solution inside the validator:

  1. Return timer(400).pipe(...). Angular unsubscribes from the previous validator Observable when a new value arrives, so the previous timer is cancelled: that is the debounce.
  2. switchMap(() => api.isTaken(value)) makes the request. Unsubscribing cancels it, so an old response is never used.
  3. map(taken => taken ? { usernameTaken: true } : null).
  4. catchError(() => of(null)): if the server fails, do not block the user forever. Decide whether a failed check means valid (as here) or an error like { checkFailed: true }.

Other points:

  • updateOn: 'blur' on the control (or { updateOn: 'blur' } in FormControl) validates when the user leaves the field. It is a simple alternative.
  • Show feedback: control.pending for "Checking...", control.hasError('usernameTaken') for the error.
  • The submit button should consider form.pending. A form that is PENDING is neither valid nor invalid, so form.invalid is false while pending. Disable submit when form.invalid || form.pending.
  • The server must still check at submit time. A client check is advice, because someone else can take the name a second later.
  • Provide the validator from a service so it can be tested with a fake API: inject(UsernameService) inside a factory function.

Test with fakeAsync: set a value, tick(400), flush the HTTP mock, then check the errors.

typescript
import { Component, Injectable, inject } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, FormControl, ReactiveFormsModule, ValidationErrors, Validators } from '@angular/forms';
import { Observable, catchError, map, of, switchMap, timer } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class UsernameService {
  isTaken(name: string): Observable<boolean> {
    return of(['asha', 'ravi'].includes(name.toLowerCase()));
  }
}

export function usernameFree(service: UsernameService): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> =>
    timer(400).pipe(
      switchMap(() => service.isTaken(control.value as string)),
      map((taken) => (taken ? { usernameTaken: true } : null)),
      catchError(() => of(null)),
    );
}

@Component({
  selector: 'app-username',
  imports: [ReactiveFormsModule],
  template: `
    <label for="u">Username</label>
    <input id="u" [formControl]="username" />
    @if (username.pending) { <small>Checking...</small> }
    @if (username.hasError('usernameTaken')) { <small role="alert">That name is taken.</small> }
    <button [disabled]="username.invalid || username.pending">Register</button>
  `,
})
export class UsernameComponent {
  private readonly service = inject(UsernameService);
  readonly username = new FormControl('', {
    nonNullable: true,
    validators: [Validators.required, Validators.minLength(3)],
    asyncValidators: [usernameFree(this.service)],
  });
}

Angular 20.3, strict template check passes. A Karma test with fakeAsync checks the pending state, the error for a taken name, and the valid result for a free name.

Key points

  • An async validator returns an Observable of errors or null, and sets the control to `PENDING`.
  • Debounce with `timer` and cancel with `switchMap`, because Angular unsubscribes from the old validator.
  • Handle errors, show a pending state, and consider `form.pending` on submit.
  • The server must check again on submit.

Common mistakes

  • Sending a request on every keystroke.
  • Letting a failed request leave the control pending forever.
  • Enabling submit while the form is pending.

Follow-ups

  • Why does Angular skip async validators when a sync validator fails?
  • How would you test the debounce?
  • What does `updateOn: 'blur'` change?

Tips

  • Explain that unsubscribing is the debounce mechanism.
  • Mention the `pending` status and the submit button.
  • Say that the server check at submit is still required.

Evaluation rubric

  • Writes a debounced, cancellable async validator.
  • Handles errors and pending state.
  • Considers testing and server validation.
131.angular-0131Mediummid

What is the difference between setValue and patchValue, how does reset behave, and what do updateOn and the emitEvent option change in reactive forms?

setValue needs a value for every control and throws if one is missing, while patchValue updates only the controls you give. reset sets values back (to null or to given values) and clears touched and dirty. updateOn chooses when a control updates (change, blur or submit), and emitEvent false stops valueChanges from firing.

Full answer

These methods work on FormControl, FormGroup and FormArray.

setValue(value): replaces the whole value. For a group, the object must contain every control, with no extra keys, or Angular throws an error. This strictness catches typos and missing fields. Use it when you have a complete object.

patchValue(value): updates only the keys you give and ignores unknown keys. Use it for partial updates, such as filling part of a form from a server response.

reset(value?): sets the value to null (or to the initial value for non-nullable controls, or to the object you pass), and marks the control pristine and untouched. It also sets status to valid or invalid again. Use it after submit. Note that reset() on a nullable control gives null, so use nonNullable controls to get empty strings back.

valueChanges and statusChanges are observables that emit when the value or status changes. Methods take options:

  • { emitEvent: false }: do not emit valueChanges. Use it when you update a field from a valueChanges handler of another field, to avoid an endless loop.
  • { onlySelf: true }: do not update parent controls' validity.

updateOn controls when the model updates from the view: 'change' (default, on every input event), 'blur' (when the field loses focus) or 'submit' (on form submit). Set it on a control, or on the whole group (new FormGroup({...}, { updateOn: 'blur' })). It reduces noisy validation and requests, because validators and valueChanges run only at that moment.

Related points: disabled controls are excluded from form.value but included in getRawValue(). markAllAsTouched() shows all errors on a failed submit. form.dirty means the user changed something, which is useful for a "leave page?" guard.

typescript
import { FormControl, FormGroup } from '@angular/forms';

export function makeForm() {
  return new FormGroup({
    name: new FormControl('', { nonNullable: true }),
    marks: new FormControl(0, { nonNullable: true }),
  });
}

export function demo(): string[] {
  const out: string[] = [];
  const form = makeForm();

  form.patchValue({ name: 'Asha' }); // only name changes
  out.push(JSON.stringify(form.value));

  try {
    // @ts-expect-error missing "marks": setValue needs every key
    form.setValue({ name: 'Ravi' });
  } catch (error) {
    out.push('setValue threw');
  }

  form.reset();
  out.push(JSON.stringify(form.value)); // nonNullable controls return to their initial values

  const onBlur = new FormControl('', { updateOn: 'blur' });
  onBlur.setValue('typed'); // programmatic changes always apply
  out.push(onBlur.value ?? '');
  return out;
}

Angular 20.3, type-checked. The function was run in a Karma test that checks the patch result, the setValue error, the reset values, and that a programmatic change applies on an updateOn blur control.

Key points

  • `setValue` needs the full shape and throws on mismatch. `patchValue` accepts partial values.
  • `reset` clears values, touched and dirty. Use `nonNullable` to reset to empty strings.
  • `emitEvent: false` stops `valueChanges`, which prevents loops.
  • `updateOn` chooses change, blur or submit for model updates and validation.

Common mistakes

  • Using `setValue` with partial data and getting an error.
  • Calling `reset()` and getting `null` instead of an empty string.
  • Updating a control inside its own `valueChanges` without `emitEvent: false`.

Follow-ups

  • Why does `form.value` omit disabled controls?
  • How would you show all validation errors after a failed submit?
  • When would you set `updateOn: 'submit'`?

Tips

  • Explain `setValue` strictness as a feature.
  • Mention `nonNullable` and `reset`.
  • Name the loop problem and its fix.

Evaluation rubric

  • Distinguishes setValue, patchValue and reset correctly.
  • Explains updateOn and emitEvent.
  • Gives practical cautions.
132.angular-0132Mediummid

How do you upgrade an Angular application to a new major version safely, and how does ng update work?

Upgrade one major version at a time with ng update, starting from a clean git state. The CLI runs migration schematics that rewrite your code for breaking changes, and the official update guide lists manual steps. Update Angular packages together, then third party libraries, run the tests, and fix deprecations before the next step.

Full answer

Angular releases a major version about every six months, with minor versions and patches between. Each major version comes with automated migrations.

Process:

  1. Prepare: commit or stash your work, make sure tests and the build pass, and read the official "Angular update guide" (update.angular.dev), which gives steps for your from and to versions and your app complexity.
  2. Update one major version at a time: ng update @angular/core@20 @angular/cli@20. Skipping majors is not supported by the schematics. The command checks peer dependencies, installs the new versions, and runs migration schematics, which edit your code (for example moving to the new control flow, standalone components, or renamed APIs). Review the diff.
  3. Update dependent libraries to compatible versions: Angular Material and CDK (ng update @angular/material@20), NgRx, and others. ng update without arguments lists what can be updated.
  4. Update TypeScript, Node and zone.js versions as required by the guide. Each Angular version supports a range of Node and TypeScript versions.
  5. Build, run unit and end to end tests, and test manually in the browser. Fix compile errors and warnings.
  6. Replace deprecated APIs at your own pace. The team keeps deprecated APIs for at least two major versions, and migrations help.
  7. Commit each major step separately, so problems are easy to find.

Useful flags: --force ignores peer dependency problems (use with care), --allow-dirty runs with uncommitted changes, --create-commits makes a commit for each migration, and --migrate-only --from=19.0.0 --to=20.0.0 reruns migrations only.

Optional migrations that are not automatic: ng generate @angular/core:standalone, @angular/core:control-flow, @angular/core:signal-input-migration, and @angular/core:inject. They modernise code gradually.

Support policy: each major has about 18 months of support (6 active, 12 long term). Planning upgrades twice a year is cheaper than a large jump after several years. When the project is very old, upgrade step by step, and consider a time-boxed rewrite of parts that cannot be migrated.

typescript
// file: package.excerpt.json
{
  "scripts": {
    "update:core": "ng update @angular/core@20 @angular/cli@20",
    "update:material": "ng update @angular/material@20",
    "migrate:standalone": "ng generate @angular/core:standalone",
    "migrate:control-flow": "ng generate @angular/core:control-flow",
    "migrate:signal-inputs": "ng generate @angular/core:signal-input-migration",
    "migrate:inject": "ng generate @angular/core:inject",
    "check:versions": "ng version"
  }
}

Angular CLI 20. This is a process answer. The snippet lists the commands as npm scripts in a package.json excerpt, and the commands were not executed against an old project here.

Key points

  • Upgrade one major version at a time with `ng update`, from a clean git state.
  • Migration schematics edit code. Review the diff. Follow the official update guide.
  • Update Material, NgRx and other libraries, then TypeScript and Node as required.
  • Test each step and commit separately. Upgrade regularly.

Common mistakes

  • Jumping several majors at once.
  • Using `--force` to skip peer dependency warnings without checking.
  • Running the update with uncommitted work.

Follow-ups

  • How would you handle a library that has no version for the new Angular?
  • What does `--migrate-only` do?
  • How long is an Angular version supported?

Tips

  • Mention the update guide website. It shows that you use official tools.
  • Describe a safe order: Angular, libraries, tests.
  • Mention the optional migration schematics.

Evaluation rubric

  • Describes a safe step by step process.
  • Knows what ng update does and key flags.
  • Understands support policy and regular upgrades.
133.angular-0133Mediummid

How does the Angular service worker (ngsw) work, how do you configure caching, and how do you handle app updates?

The Angular service worker is a script that sits between the app and the network and caches the app shell, assets and chosen API responses according to ngsw-config.json. It checks for a new version in the background, and the app can ask users to reload with SwUpdate. It only works over HTTPS and in production builds.

Full answer

A service worker is a script the browser runs in the background, separate from the page. It can intercept network requests, so it can answer from a cache when the network is slow or missing. Angular provides @angular/service-worker, added with ng add @angular/pwa, which also adds a web app manifest and icons.

Set-up:

  • provideServiceWorker('ngsw-worker.js', { enabled: !isDevMode(), registrationStrategy: 'registerWhenStable:30000' }) in the app config.
  • ngsw-config.json describes caching. assetGroups cache the app files: app (the shell, prefetch) and assets (images and fonts, lazy). dataGroups cache API calls with a strategy: freshness (network first, fall back to cache after a timeout) or performance (cache first, refresh after maxAge), plus maxSize and maxAge.
  • The build produces ngsw.json, a manifest with hashes of every file. The worker uses it to know exactly what version it has.

Update flow:

  1. On start the worker fetches ngsw.json in the background.
  2. If the hashes changed, it downloads the new files into a new version, but keeps serving the old version to open tabs, so the page never mixes files from two versions.
  3. The app can listen to SwUpdate.versionUpdates for a VERSION_READY event and show "A new version is available. Reload". Then document.location.reload() or swUpdate.activateUpdate() followed by a reload switches to the new version.
  4. For long-lived tabs, call swUpdate.checkForUpdate() on a timer.

Cautions:

  • It works only on HTTPS (or localhost) and does nothing with ng serve. Test with a production build served by a static server.
  • Cached index.html can keep users on an old version, so always give an update prompt.
  • Never cache authenticated API responses that differ per user without care, and clear caches on logout (caches API).
  • A broken service worker is hard to remove. Keep the "safety worker" (safety-worker.js) in mind and test updates.
  • Do not cache everything. A large cache costs storage and can show stale data.
typescript
// file: app.config.ts
import { ApplicationConfig, isDevMode } from '@angular/core';
import { provideServiceWorker } from '@angular/service-worker';

export const appConfig: ApplicationConfig = {
  providers: [
    provideServiceWorker('ngsw-worker.js', {
      enabled: !isDevMode(),
      registrationStrategy: 'registerWhenStable:30000',
    }),
  ],
};

// file: ngsw-config.json
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    { "name": "app", "installMode": "prefetch", "resources": { "files": ["/favicon.ico", "/index.html", "/*.css", "/*.js"] } },
    { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": ["/assets/**", "/*.(svg|png|webp|woff2)"] } }
  ],
  "dataGroups": [
    { "name": "courses-api", "urls": ["/api/courses/**"], "cacheConfig": { "strategy": "freshness", "maxSize": 50, "maxAge": "1h", "timeout": "3s" } }
  ]
}

Angular 20.3 with `@angular/service-worker` 20.3, type-checked. The config files are examples and were not run in a browser here, so offline behaviour was not tested.

Key points

  • The service worker intercepts requests and serves from cache, using `ngsw-config.json` rules and the generated `ngsw.json` manifest.
  • `assetGroups` for files, `dataGroups` for API calls (freshness or performance).
  • Updates download in the background. `SwUpdate` lets the app prompt a reload.
  • Needs HTTPS and a production build. Be careful with user-specific data in caches.

Common mistakes

  • Testing the service worker with `ng serve` and finding nothing happens.
  • Not showing an update prompt, so users stay on an old version.
  • Caching user-specific API data without clearing it on logout.

Follow-ups

  • What is the difference between `freshness` and `performance` strategies?
  • How does the worker avoid mixing files from two versions?
  • How would you test offline behaviour?

Tips

  • Describe the update flow step by step. It is the usual question.
  • Mention HTTPS and production only.
  • Mention privacy of cached data.

Evaluation rubric

  • Explains how the worker and ngsw.json work.
  • Knows configuration groups and strategies.
  • Handles updates and risks.
134.angular-0134Mediummid

How do you configure an Angular app without NgModules, using bootstrapApplication, ApplicationConfig and provide functions?

bootstrapApplication takes the root component and an ApplicationConfig whose providers array holds provide functions such as provideRouter, provideHttpClient and provideZonelessChangeDetection. Features are passed as extra arguments (withComponentInputBinding, withInterceptors). Configs can be merged for server rendering or tests.

Full answer

Without modules, the app is started in main.ts:

bootstrapApplication(AppComponent, appConfig)

appConfig has type ApplicationConfig and contains providers. Each concern has a provide... function, and optional behaviour is added with with... feature functions:

  • provideRouter(routes, withComponentInputBinding(), withViewTransitions(), withPreloading(PreloadAllModules)).
  • provideHttpClient(withFetch(), withInterceptors([authInterceptor])). In the newest Angular versions fetch is the default backend and withFetch() is deprecated, so you only add withInterceptors(...) there.
  • provideZonelessChangeDetection() (stable from 20.2) or provideZoneChangeDetection({ eventCoalescing: true }).
  • provideBrowserGlobalErrorListeners() for global errors.
  • provideClientHydration(withEventReplay()) for server rendering.
  • provideAppInitializer(() => ...) for start-up work.
  • { provide: ErrorHandler, useClass: ... } and your own tokens.

Environment injector: these providers go in the root environment injector, so services are shared by the whole app. Providers on components or routes add narrower scopes.

Why this design: each feature is a function that can be tree-shaken, features compose through arguments, and there is no hidden global module state. It also makes testing easy: TestBed.configureTestingModule({ providers: [provideRouter([]), provideHttpClient()] }).

Combining configs: mergeApplicationConfig(appConfig, serverConfig) joins providers. For server rendering the server file bootstraps with mergeApplicationConfig(appConfig, { providers: [provideServerRendering()] }).

Other entry points: createApplication(config) creates an app without a root component, which is used for Angular Elements, and ApplicationRef.bootstrap can attach several roots. If you still have NgModules from a library, use importProvidersFrom(SomeModule) inside providers.

Keep appConfig small and ordered logically: routing, HTTP, change detection, UI, and observability. Order of unrelated providers does not matter, but for the same token the last one wins.

typescript
import { ApplicationConfig, ErrorHandler, mergeApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { Routes, provideRouter, withComponentInputBinding, withViewTransitions } from '@angular/router';
import { HttpInterceptorFn } from '@angular/common/http';

const authInterceptor: HttpInterceptorFn = (req, next) => next(req);

class AppErrorHandler implements ErrorHandler {
  handleError(error: unknown): void {
    console.error(error);
  }
}

export const routes: Routes = [];

export const appConfig: ApplicationConfig = {
  providers: [
    provideZonelessChangeDetection(),
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding(), withViewTransitions()),
    provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
    { provide: ErrorHandler, useClass: AppErrorHandler },
  ],
};

// A second config, merged with the first (for example the server part of SSR).
export const serverConfig: ApplicationConfig = { providers: [] };
export const mergedConfig = mergeApplicationConfig(appConfig, serverConfig);

// main.ts:  bootstrapApplication(AppComponent, appConfig).catch(console.error);

Angular 20.3, type-checked. A Karma test checks the provider count and that the router and HTTP client providers from the list can be injected in TestBed. The full bootstrap was not run.

Key points

  • `bootstrapApplication(Root, appConfig)` starts a standalone app. Providers come from `provide...` and `with...` functions.
  • They go into the root environment injector. They are tree-shakable and easy to test.
  • `mergeApplicationConfig` combines configs, for example for SSR.
  • Use `importProvidersFrom` for legacy modules.

Common mistakes

  • Providing the same token twice and not realising the last wins.
  • Putting feature functions outside the matching provide function, for example `withInterceptors` alone.
  • Importing a legacy module's providers without `importProvidersFrom`.

Follow-ups

  • How do you test a service that needs the router and HTTP client?
  • What does `createApplication` give you that `bootstrapApplication` does not?
  • How does the server entry reuse the browser config?

Tips

  • Name the "provide plus with" pattern.
  • Show you know zoneless is a provider.
  • Mention testing and merging configs.

Evaluation rubric

  • Describes bootstrapApplication and ApplicationConfig.
  • Names common provide and with functions.
  • Knows merge, legacy module and testing options.
135.angular-0135Hardsenior

How does Angular decide which views to check during change detection, and what do default, OnPush, signals and the dirty flag have to do with it?

Each component has a view (LView) with flags. Default views are checked on every pass. An OnPush view is checked only when it is marked dirty: an input reference changed, an event came from the template, markForCheck was called, an async pipe emitted, or a signal read in its template changed. Signals give each view a reactive consumer, so only views that read a changed signal are refreshed.

Full answer

Angular's template functions run in "update mode" for a view when it is checked. The question is which views are checked on a pass.

Default strategy: every view in the tree is checked on every pass, from the root down. That costs time in large trees, but it is simple and correct.

OnPush strategy: the view is checked only when it is dirty (or on the first pass). A view becomes dirty when:

  1. One of its inputs receives a new value (compared with ===). Mutating an object in place does not change the reference, so nothing happens.
  2. An event handler in its template (or a host listener) runs, for that view and its ancestors.
  3. ChangeDetectorRef.markForCheck() is called, which marks the view and its parents.
  4. The async pipe receives a value (it calls markForCheck).
  5. A signal read in its template changes. Since Angular 17, each view's template acts as a reactive consumer. When a signal that was read during the last check changes, the view is marked for refresh (a lighter flag than dirty, applied to this view and the path to the root so the pass reaches it).

A pass walks from the root, but it skips children of an OnPush view that is not dirty and has no refresh flag. This is why OnPush together with signals is the efficient model: a signal change refreshes one view, and its ancestors are only traversed.

Other details:

  • ngDoCheck of a child runs even when an OnPush child is skipped, because the parent calls it. Use it carefully.
  • Template functions are cheap when nothing changed: each binding compares to the previous value and touches the DOM only for differences.
  • checkNoChanges in development runs a second pass to catch bindings that change during the pass (ExpressionChangedAfterItHasBeenChecked).
  • Zoneless mode removes the "run a pass after every async task" trigger. Passes run when signals, markForCheck or events notify the scheduler.

Interview answer shape: name the two strategies, list the dirty triggers, explain how signals attach to views, and say how this reduces work.

typescript
import { ChangeDetectionStrategy, Component, input, signal } from '@angular/core';

export const renders = { child: 0 };

@Component({
  selector: 'app-score-view',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>{{ tick() }} {{ student().name }}: {{ student().marks }} {{ viaSignal() }}</p>`,
})
export class ScoreViewComponent {
  readonly student = input.required<{ name: string; marks: number }>();
  readonly viaSignal = input.required<number>();

  tick(): string {
    renders.child++; // counts how often this template is evaluated
    return '';
  }
}

@Component({
  selector: 'app-score-page',
  imports: [ScoreViewComponent],
  template: `<app-score-view [student]="student" [viaSignal]="bonus()" />`,
})
export class ScorePageComponent {
  student = { name: 'Asha', marks: 70 };
  readonly bonus = signal(0);

  mutateInPlace(): void {
    this.student.marks = 80; // same reference: OnPush child is not refreshed
  }

  replaceReference(): void {
    this.student = { ...this.student, marks: 90 };
  }
}

Angular 20.3, strict template check passes. A Karma test counts template evaluations: an OnPush child is not re-rendered when the parent mutates an object, but is when a signal it reads changes.

Key points

  • Default views are checked every pass. OnPush views only when dirty or refreshed.
  • Dirty triggers: new input reference, template event, `markForCheck`, async pipe, changed signal read in the template.
  • Signals give each view a reactive consumer, so only affected views refresh.
  • Mutating objects in place does not trigger OnPush. Use new references or signals.

Common mistakes

  • Mutating an input object and expecting an OnPush child to update.
  • Believing OnPush skips `ngDoCheck` of the child.
  • Calling `detectChanges` to compensate for broken data flow.

Follow-ups

  • Why does an event in a child mark its ancestors?
  • How does zoneless mode decide when to run a pass?
  • What does `ExpressionChangedAfterItHasBeenChecked` indicate?

Tips

  • List the five dirty triggers from memory.
  • Say that signals mark views, not components globally.
  • Mention development mode's second pass.

Evaluation rubric

  • Explains default versus OnPush correctly.
  • Lists dirty triggers including signals.
  • Understands the traversal and its cost.
136.angular-0136Hardsenior

How do you write a custom preloading strategy that loads only selected lazy routes, for example on good connections or when a route is marked as important?

A PreloadingStrategy has one method, preload(route, load), which returns the load observable to start loading now or EMPTY to skip. Use route data flags and conditions such as the network type and the Save-Data setting to choose, and enable the strategy with withPreloading.

Full answer

Lazy loading keeps the first download small. The cost is a delay when the user first opens a lazy route. Preloading downloads lazy chunks in the background after the first render, so later navigation is instant.

Built in: PreloadAllModules (loads everything) and NoPreloading (the default). Loading everything wastes data on mobile networks, and loading nothing makes navigation slow. A custom strategy chooses.

Implementation: a class that implements PreloadingStrategy:

preload(route: Route, load: () => Observable<any>): Observable<any>

Return load() to preload the route, or of(null) / EMPTY to skip it. The router calls this for each lazy route after navigation ends.

Typical rules:

  • Only routes with data: { preload: true }.
  • Skip when the user wants less data: navigator.connection?.saveData, or an effective type of 2g or slow-2g. The Network Information API is not available in all browsers, so guard for undefined.
  • Add a delay (timer(2000).pipe(mergeMap(() => load()))) so preloading does not compete with the first page's work.
  • Preload by priority or in order, with concatMap.
  • For very large apps, predict the next route from analytics, or preload on hover with routerLink and a link directive (a third party option).

Enable with provideRouter(routes, withPreloading(SelectivePreloading)). The class is created by the injector, so it can inject services.

Server rendering: preloading is a browser concern. Guard with isPlatformBrowser so the server does not try to load chunks it does not need.

Measure the result: check the Network panel for which chunks load after start, and compare time to interactive for the first navigation with and without the strategy. Do not preload admin pages that most users never open.

typescript
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { EMPTY, Observable, mergeMap, timer } from 'rxjs';

interface NetworkInfo {
  saveData?: boolean;
  effectiveType?: string;
}

export function shouldPreload(route: Route, network: NetworkInfo | undefined): boolean {
  if (route.data?.['preload'] !== true) {
    return false;
  }
  if (network?.saveData) {
    return false;
  }
  return network?.effectiveType !== '2g' && network?.effectiveType !== 'slow-2g';
}

@Injectable({ providedIn: 'root' })
export class SelectivePreloading implements PreloadingStrategy {
  preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
    const network = (navigator as Navigator & { connection?: NetworkInfo }).connection;
    if (!shouldPreload(route, network)) {
      return EMPTY;
    }
    return timer(2000).pipe(mergeMap(() => load()));
  }
}

// provideRouter(routes, withPreloading(SelectivePreloading))
// { path: 'reports', loadComponent: () => import('./reports'), data: { preload: true } }

Angular 20.3, type-checked. The strategy was not run against a real router here. The decision function is separated so it could be unit tested.

Key points

  • `PreloadingStrategy.preload(route, load)` returns `load()` to preload or `EMPTY` to skip.
  • Choose with route `data`, network conditions, and a delay.
  • Enable with `withPreloading(Strategy)`. Guard browser-only APIs.
  • Measure in the Network panel. Do not preload rarely used routes.

Common mistakes

  • Using `PreloadAllModules` on a large app and wasting mobile data.
  • Reading `navigator.connection` without checking it exists.
  • Preloading immediately and competing with the first page's work.

Follow-ups

  • How would you preload a route when the user hovers a link?
  • How does preloading interact with route guards like `canMatch`?
  • How do you measure the benefit?

Tips

  • Mention Save-Data and slow networks. It shows real-world thinking.
  • Say you add a delay.
  • Offer measurement as the way to prove value.

Evaluation rubric

  • Implements the interface correctly.
  • Uses sensible conditions and guards unsupported APIs.
  • Enables it and measures impact.
137.angular-0137Hardsenior

What are Angular schematics, and how would you write one that generates a feature or supports ng add and ng update?

A schematic is a function that receives a virtual file system Tree and a context, and returns a modified Tree. Collections list schematics in collection.json. ng generate runs one, ng add runs the add schematic of a package, and ng update runs migration schematics. They let teams enforce structure and automate code changes.

Full answer

Schematics are the code generators and transformers behind the CLI. ng generate component runs a schematic. Teams write their own to create features in a standard shape, to install libraries, and to migrate code.

Core ideas:

  • A schematic is a rule: a function (tree: Tree, context: SchematicContext) => Tree | Observable<Tree> | Rule. The Tree is an in-memory copy of the project's files. Changes are only written to disk when the whole schematic succeeds, so a failure leaves nothing half done. A dry run (--dry-run) shows the changes.
  • Utilities compose rules: apply(url('./files'), [template({...}), move(path)]) reads template files (names like __name@dasherize__.component.ts.template), replaces placeholders, and mergeWith adds them. chain([...]) runs rules in order.
  • A collection.json maps schematic names to factory functions and a schema.json that describes options and prompts (name, project, path). Angular's @schematics/angular utilities help find the default project and path, and ts-morph or the TypeScript API edits existing code safely.

Three kinds:

  1. Generate: ng generate my-lib:feature orders creates files from templates.
  2. ng add: the package declares "ng-add": { "save": "dependencies" } and a schematic named ng-add that edits angular.json, adds providers to the app config, and installs peer packages.
  3. ng update: package.json has ng-update with migrations pointing to a migrations.json. Each migration has a version and a function that edits code for breaking changes, so users get automated upgrades.

Practical advice:

  • Keep templates small and close to real code, and keep a sample project to test against.
  • Test with SchematicTestRunner from @angular-devkit/schematics/testing, using a virtual tree.
  • Edit code with AST tools, not regular expressions.
  • Make schematics idempotent where possible (running twice does not break the project).
  • Nx generators serve the same role in Nx workspaces.
typescript
// file: feature/index.ts
import { Rule, SchematicContext, Tree, apply, chain, mergeWith, move, strings, template, url } from '@angular-devkit/schematics';

interface FeatureOptions {
  name: string;
  path: string;
}

export function feature(options: FeatureOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    context.logger.info(`Creating feature ${options.name}`);
    const source = apply(url('./files'), [
      template({ ...strings, ...options }),
      move(`${options.path}/${strings.dasherize(options.name)}`),
    ]);
    return chain([mergeWith(source)])(tree, context);
  };
}

// file: collection.json
{
  "schematics": {
    "feature": {
      "description": "Creates a feature folder",
      "factory": "./feature/index#feature",
      "schema": "./feature/schema.json"
    },
    "ng-add": {
      "description": "Adds the library to a project",
      "factory": "./ng-add/index#ngAdd"
    }
  }
}

Angular 20.3 with `@angular-devkit/schematics` 20, type-checked. The schematic was not run through the CLI or the test runner here.

Key points

  • A schematic is a rule that transforms a virtual `Tree`, and changes apply only if it succeeds.
  • `collection.json` and `schema.json` register schematics and describe options.
  • Generate, `ng add` and `ng update` migrations are the three uses.
  • Test with `SchematicTestRunner`. Use AST tools. Keep schematics idempotent.

Common mistakes

  • Editing source files with regular expressions.
  • Writing schematics that cannot run twice safely.
  • Not testing against a sample workspace.

Follow-ups

  • How would you add a provider to `app.config.ts` from a schematic?
  • How does `ng update` know which migrations to run?
  • When would you choose an Nx generator?

Tips

  • Explain the virtual Tree and why it is safe.
  • Name the three uses.
  • Mention testing and AST editing.

Evaluation rubric

  • Explains Tree, rules and collections.
  • Covers generate, add, and update schematics.
  • Gives testing and safety advice.
138.angular-0138Hardsenior

How do you deploy an Angular app to a static host or CDN, and how do SPA fallback, caching headers, base href and hashed file names fit together?

ng build outputs static files with content hashes in their names. Serve index.html with no-cache so users get new versions, serve hashed JS and CSS with a long immutable cache, send unknown paths back to index.html for client side routes, and set the base href when the app lives under a sub path.

Full answer

A client-side Angular app is a set of static files. The deployment problems are routing, caching, and versions.

Build output: with ng build (production configuration) the files in the browser folder have content hashes: main-AB12CD34.js. The name changes whenever the content changes. index.html references these names.

  1. SPA fallback. A URL like /courses/42 exists only in the router, not as a file. A request for it must return index.html, and then the router renders the right page. Configure the server: nginx try_files $uri $uri/ /index.html;, a rewrite on a CDN, or the static host's "single page app" setting. Real missing assets (a .js or .png that does not exist) should still return 404, so do not rewrite those.
  2. Caching. Hashed files can be cached for a year with Cache-Control: public, max-age=31536000, immutable, because a new version has a new name. index.html must not be cached for long: Cache-Control: no-cache (revalidate every time), or a very short max-age. If index.html is cached, users stay on an old version, and may request hashed files that you already deleted.
  3. Old versions. Keep old hashed files for a while after a deployment. A user with an open old tab may still load a lazy chunk from the previous version, which would 404 if deleted. This is also why a "new version available" prompt helps (service worker or version check).
  4. Base href. If the app is served from https://example.com/school/, build with --base-href /school/ and make sure the server fallback points to that index.html. Relative asset URLs and the router depend on it.
  5. Compression and protocols: gzip or brotli, HTTP/2 or 3, and a CDN close to users.
  6. Environment config: for one build many environments, load a config.json at start-up (not cached) instead of rebuilding.
  7. Server rendering changes this: you deploy a Node server (or edge function) plus static files, and caching rules apply to HTML responses too.

CI/CD checklist: build once, run tests, publish the artifact, deploy to staging, run smoke tests, promote the same artifact to production, and keep a rollback path (previous version still available).

typescript
// file: headers.ts
export function cacheControlFor(path: string): string {
  if (path === '/' || path.endsWith('.html') || path.endsWith('config.json')) {
    return 'no-cache';
  }
  if (/-[A-Za-z0-9]{8}\.(js|css|woff2|png|svg|webp)$/.test(path)) {
    return 'public, max-age=31536000, immutable';
  }
  return 'public, max-age=3600';
}

for (const p of ['/', '/index.html', '/main-AB12CD34.js', '/favicon.ico', '/config.json']) {
  console.log(p.padEnd(20), cacheControlFor(p));
}

// file: nginx.conf
server {
  listen 80;
  root /usr/share/nginx/html;
  index index.html;

  location = /index.html { add_header Cache-Control "no-cache"; }
  location ~* \.(js|css|woff2|png|svg|webp)$ {
    try_files $uri =404;                       # missing assets stay 404
    add_header Cache-Control "public, max-age=31536000, immutable";
  }
  location / { try_files $uri $uri/ /index.html; }   # client side routes
}

The sample is an nginx configuration and a headers helper. The helper function was run in Node twice with identical output. The nginx file is an example and was not run against a server here.

Key points

  • Hashed file names allow long immutable caching. `index.html` must be revalidated.
  • SPA fallback returns `index.html` for client routes but still returns 404 for missing assets.
  • Keep old chunks for a while. Set `--base-href` for sub paths.
  • Build once, promote the same artifact, and keep a rollback.

Common mistakes

  • Caching `index.html` for a long time and trapping users on an old version.
  • Rewriting every 404 (including missing JS files) to `index.html`.
  • Deleting old chunks immediately after deployment.

Follow-ups

  • Why does a missing chunk cause a "ChunkLoadError", and how do you handle it?
  • How does the base href affect the router and assets?
  • What changes when you add SSR?

Tips

  • State the hashed names plus long cache plus no-cache `index.html` rule.
  • Mention old chunks and open tabs.
  • End with the build-once promote-many practice.

Evaluation rubric

  • Covers fallback, caching, base href and versions correctly.
  • Explains the reasons, not only settings.
  • Mentions CI/CD practices.
139.angular-0139Hardsenior

Write a service that checks for service worker updates, prompts the user when a new version is ready, and recovers from an unrecoverable state.

Inject SwUpdate, listen to versionUpdates for VERSION_READY and show a prompt, call checkForUpdate on a timer for long lived tabs, reload after the user accepts (activateUpdate then location.reload), and handle unrecoverable events by reloading, because the cached files no longer match.

Full answer

The service worker downloads a new version in the background but keeps serving the old one until the page is reloaded. A good update service completes the loop.

Parts:

  1. SwUpdate.isEnabled: false in development and in browsers without support. Guard everything with it.
  2. versionUpdates: an observable of events: VERSION_DETECTED (a new version started downloading), VERSION_READY (downloaded, ready to activate), VERSION_INSTALLATION_FAILED, and NO_NEW_VERSION_DETECTED. Filter for VERSION_READY and set a signal updateReady that the UI shows as "A new version is available".
  3. Accept: await swUpdate.activateUpdate() then document.location.reload(). Activating without reload would give new files to an old page, which can break lazy chunk loads.
  4. Periodic checks: the worker checks on start. A tab left open for days needs checkForUpdate() on a timer, for example every 6 hours, or when the tab becomes visible again. Run the timer outside Angular's zone, or with interval and takeUntilDestroyed, and avoid timers that keep the app unstable, which would delay the registerWhenStable strategy (use afterNextRender or start after ApplicationRef.isStable).
  5. unrecoverable: an event that tells you the worker's cache is corrupt or files went missing. The page can no longer trust cached assets, so inform the user and reload.

Design notes:

  • Do not force a reload without warning, since the user may lose form input. Prompt, and let the user choose, or reload on a safe navigation.
  • For critical fixes, a version check API (a small JSON file with the minimum version) can force the prompt.
  • Test with a production build served over localhost, change a file, rebuild, and watch the update flow in the browser's Application tab.
  • Log events to monitoring, to see how many users run old versions.
typescript
import { DestroyRef, Injectable, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter, interval } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AppUpdateService {
  private readonly sw = inject(SwUpdate);
  private readonly destroyRef = inject(DestroyRef);

  readonly updateReady = signal(false);
  readonly broken = signal(false);

  constructor() {
    if (!this.sw.isEnabled) {
      return;
    }

    this.sw.versionUpdates
      .pipe(
        filter((e): e is VersionReadyEvent => e.type === 'VERSION_READY'),
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe(() => this.updateReady.set(true));

    this.sw.unrecoverable.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.broken.set(true));

    interval(6 * 60 * 60 * 1000)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => void this.sw.checkForUpdate());
  }

  async applyUpdate(): Promise<void> {
    await this.sw.activateUpdate();
    document.location.reload();
  }
}

Angular 20.3 with `@angular/service-worker` 20.3, type-checked. It was not run in a browser here, because that needs a production build served over HTTP with a real service worker.

Key points

  • Guard with `SwUpdate.isEnabled`. Listen to `versionUpdates` for `VERSION_READY`.
  • Prompt, then `activateUpdate()` and reload. Do not activate without reloading.
  • Check periodically for long lived tabs. Handle `unrecoverable`.
  • Avoid surprise reloads. Test with a production build.

Common mistakes

  • Activating an update without reloading the page.
  • Starting an endless timer that stops the app from becoming stable.
  • Forcing a reload and losing the user's input.

Follow-ups

  • What does `registerWhenStable` do and how can a timer break it?
  • How would you require a minimum version?
  • How would you test the update flow?

Tips

  • Name the event types.
  • Mention the lost input problem.
  • Say you log update events.

Evaluation rubric

  • Uses SwUpdate events correctly.
  • Implements prompt, activation and reload.
  • Handles unrecoverable state and periodic checks.
140.angular-0140Hardsenior

How do route-level providers and environment injectors work, and how do you create an injector at run time for isolated state?

A route's providers array creates an environment injector for that route and its children, so services live as long as the route and are separate from the root. You can also build an injector at run time with createEnvironmentInjector, and use runInInjectionContext to call functions that use inject() with it.

Full answer

Besides the root injector, Angular has environment injectors that are created for parts of the app.

Route providers:

{ path: 'checkout', providers: [CartDraftService], children: [...] }

The router creates an environment injector for this route and its children, as a child of the injector of the parent route (or root). CartDraftService is created when first injected, shared by all components in these routes, and destroyed when the route is deactivated for good (its ngOnDestroy runs). Benefits: state scoped to a flow (checkout, wizard), lazy loaded features that bring their own services, and different configuration per area (for example a different API_URL token for the admin area). With loadChildren the providers also arrive with the lazy chunk.

Run-time injectors:

  • createEnvironmentInjector(providers, parentInjector) makes an injector from providers. Use it for plugin-like or dialog-like features that need their own services. Pass it to createComponent(Component, { environmentInjector }) or to ViewContainerRef.createComponent. Destroy it with injector.destroy() when done, which runs ngOnDestroy of its services.
  • runInInjectionContext(injector, () => inject(Service)) runs a function with an injector active, so functions that call inject() can be used outside constructors, for example in a callback or a test.
  • EnvironmentInjector itself can be injected, and inject(EnvironmentInjector).get(Token) is the safe service locator for rare cases.

Lookup rules: a component first checks its element injector tree, then the environment injector chain for the route, then root, then platform. A child environment injector can override a token from the parent for its subtree only.

Pitfalls: an injector that you create must be destroyed, or services leak. Services provided in a route are not available to components outside it. Stateful route providers are recreated when the route is left and entered again, unless the router reuses the route.

typescript
import { EnvironmentInjector, Injectable, InjectionToken, OnDestroy, createEnvironmentInjector, inject, runInInjectionContext } from '@angular/core';
import { Routes } from '@angular/router';

export const API_URL = new InjectionToken<string>('API_URL', { factory: () => '/api' });

@Injectable()
export class DraftService implements OnDestroy {
  destroyed = false;
  ngOnDestroy(): void {
    this.destroyed = true;
  }
}

export const routes: Routes = [
  {
    path: 'admin',
    providers: [{ provide: API_URL, useValue: '/admin-api' }, DraftService],
    loadChildren: () => Promise.resolve([] as Routes),
  },
];

export function withTemporaryInjector(parent: EnvironmentInjector): { url: string; draft: DraftService } {
  const child = createEnvironmentInjector([{ provide: API_URL, useValue: '/preview-api' }, DraftService], parent);
  const result = runInInjectionContext(child, () => ({ url: inject(API_URL), draft: inject(DraftService) }));
  child.destroy(); // runs ngOnDestroy of DraftService
  return result;
}

Angular 20.3, type-checked. A Karma test checks that a child injector overrides the token and that `destroy()` runs the service's ngOnDestroy.

Key points

  • Route `providers` create an environment injector scoped to the route and its children.
  • `createEnvironmentInjector` builds an injector at run time. Destroy it when finished.
  • `runInInjectionContext` lets `inject()` work in a callback with a chosen injector.
  • Child injectors override tokens for their subtree only.

Common mistakes

  • Creating an injector and never destroying it.
  • Expecting route-provided services to be available outside the route.
  • Using the injector as a general service locator everywhere.

Follow-ups

  • When is a route's environment injector destroyed?
  • How would you give the admin area a different API URL?
  • How do dialogs get their own injector?

Tips

  • Use checkout state as the example for route providers.
  • Mention `destroy()`.
  • Mention the lookup order from element to environment injectors.

Evaluation rubric

  • Explains route providers and lifetimes.
  • Uses createEnvironmentInjector and runInInjectionContext correctly.
  • Covers cleanup and lookup order.