← Interview prep

Angular interview questions

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

195 questions · Page 5 of 10

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

Page 5 of 10

Questions 81–100 of 195 · 0 of 20 on this page marked learned

81.angular-0081Mediummid

Write an HTTP interceptor that retries failed GET requests with exponential backoff, respects Retry-After, and does not retry unsafe requests. How do you test it?

Retry only idempotent requests (GET and HEAD) on transient failures such as network errors, 429, 502, 503 and 504. Use retry with a delay function that uses the Retry-After header when present and exponential backoff otherwise, cap the attempts, and rethrow other errors immediately. Test it with HttpTestingController and fakeAsync.

Full answer

A retry interceptor must be careful. Retrying the wrong request or retrying too fast can make an outage worse or duplicate a payment.

Rules for a safe design:

  1. Which requests: only safe, idempotent methods (GET, HEAD). A POST can create two orders if retried. PUT and DELETE are idempotent by definition, but retry them only if your API guarantees it.
  2. Which errors: network failure (status === 0), 429, 502, 503, and 504. Never retry 400, 401, 403, 404, or 422, because they will fail the same way.
  3. How many: a small number, for example 3.
  4. How long to wait: exponential backoff (base * 2^(attempt - 1)), capped at a maximum. Add random jitter in production so many clients do not retry together. If the server sends Retry-After (seconds), wait that long.
  5. Opt-out: let a request disable retries, for example with an HttpContextToken.

Implementation with RxJS 7: retry({ count, delay }). The delay callback receives the error and the attempt number, and returns an Observable that emits when to retry. To stop retrying for an error, return throwError(() => error) from it. The interceptor is a function, so it can inject() settings.

Testing: provide HttpClient, the testing backend, and the interceptor. Use fakeAsync: call get, expectOne(url).flush('', { status: 503, statusText: 'Unavailable' }), then tick(delay) and expectOne again. Assert the number of attempts, that 404 is not retried, and that POST is not retried. Call http.verify() at the end.

Where else it lives: some teams retry inside a service for chosen calls only, since a global retry may hide problems. Show user feedback (a "retrying" message) for long delays.

typescript
// file: retry.interceptor.ts
import { HttpContextToken, HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { Observable, retry, throwError, timer } from 'rxjs';

export const MAX_RETRIES = new HttpContextToken<number>(() => 3);

const RETRYABLE_STATUS = new Set([0, 429, 502, 503, 504]);
const BASE_DELAY_MS = 100;
const MAX_DELAY_MS = 5000;

function delayFor(error: unknown, attempt: number): Observable<number> {
  if (!(error instanceof HttpErrorResponse) || !RETRYABLE_STATUS.has(error.status)) {
    return throwError(() => error);
  }
  const retryAfter = Number(error.headers.get('Retry-After'));
  const wait = Number.isFinite(retryAfter) && retryAfter > 0
    ? retryAfter * 1000
    : Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_DELAY_MS);
  return timer(wait);
}

export const retryInterceptor: HttpInterceptorFn = (req, next) => {
  const safe = req.method === 'GET' || req.method === 'HEAD';
  const count = safe ? req.context.get(MAX_RETRIES) : 0;
  return next(req).pipe(retry({ count, delay: delayFor }));
};

// file: retry.interceptor.spec.ts
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { retryInterceptor } from './retry.interceptor';

describe('retryInterceptor', () => {
  let http: HttpClient;
  let backend: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(withInterceptors([retryInterceptor])), provideHttpClientTesting()],
    });
    http = TestBed.inject(HttpClient);
    backend = TestBed.inject(HttpTestingController);
  });

  afterEach(() => backend.verify());

  it('retries a GET after 503 with backoff and then succeeds', fakeAsync(() => {
    let result: unknown;
    http.get('/api/data').subscribe((r) => (result = r));

    backend.expectOne('/api/data').flush('', { status: 503, statusText: 'Unavailable' });
    tick(100); // first backoff
    backend.expectOne('/api/data').flush('', { status: 503, statusText: 'Unavailable' });
    tick(200); // second backoff
    backend.expectOne('/api/data').flush({ ok: true });

    expect(result).toEqual({ ok: true });
  }));

  it('does not retry a 404', fakeAsync(() => {
    let status = 0;
    http.get('/api/missing').subscribe({ error: (e) => (status = e.status) });

    backend.expectOne('/api/missing').flush('', { status: 404, statusText: 'Not Found' });
    tick(10000);

    expect(status).toBe(404);
  }));

  it('does not retry a POST', fakeAsync(() => {
    let status = 0;
    http.post('/api/orders', {}).subscribe({ error: (e) => (status = e.status) });

    backend.expectOne('/api/orders').flush('', { status: 503, statusText: 'Unavailable' });
    tick(10000);

    expect(status).toBe(503);
  }));
});

Angular 20.3 and RxJS 7, type-checked, and the spec was run in headless Chrome with `ng test`, and all three specs pass. The delays are 100 ms base so the spec is fast.

Key points

  • Retry only GET and HEAD, and only for transient errors (0, 429, 502, 503, 504).
  • Use `retry({ count, delay })` with exponential backoff, a cap, and `Retry-After`.
  • Return `throwError` from `delay` to stop retrying.
  • Test with `HttpTestingController` and `fakeAsync` with `tick`.

Common mistakes

  • Retrying POST requests, which can duplicate side effects.
  • Retrying on 4xx errors that will never succeed.
  • Retrying immediately without a delay, increasing load on a failing server.

Follow-ups

  • Why add jitter to the backoff?
  • How would you let one request opt out of retries?
  • How would you show the user that a retry is happening?

Tips

  • Start with what you will not retry. It shows engineering judgement.
  • Mention idempotency by name.
  • Say that you test the "no retry" cases as carefully as the retry cases.

Evaluation rubric

  • Chooses requests and errors to retry with reasons.
  • Implements backoff and Retry-After correctly.
  • Tests with fakeAsync and verify.
82.angular-0082Mediummid

Build a tags input component that works with reactive forms. How do you implement both ControlValueAccessor and Validator?

Provide the component with NG_VALUE_ACCESSOR so forms can read and write its string array, and with NG_VALIDATORS so the control can report errors such as too many tags. The component keeps its tags in a signal, calls the registered change function when the user adds or removes a tag, and reports touched on blur.

Full answer

A tags input shows chips and lets the user type new ones. The form value is string[].

ControlValueAccessor (CVA) part: the same four methods as any custom control.

  • writeValue(tags) receives the value from the form and stores it in a signal. It must not call the change function.
  • registerOnChange(fn) stores the callback. Call it with a new array whenever the user adds or removes a tag.
  • registerOnTouched(fn) stores the callback, called on blur.
  • setDisabledState(disabled) disables the input and the remove buttons.

Validator part. A custom control can also validate itself. Implement the Validator interface (validate(control) returns null or an error object), and register the component under NG_VALIDATORS with multi: true. Then Validators on the control and the component's own rules combine. In the example, validate returns { maxTags: { max, actual } } when there are too many tags and { duplicate: true } is prevented at the input level instead. The component's max input is a signal, so when it changes call the stored onValidatorChange callback (from registerOnValidatorChange), so the form re-validates.

Behaviour: Enter or comma adds a trimmed, non-empty, unique tag. Backspace on an empty input removes the last tag. Each chip has a remove button with a label such as "Remove angular".

Accessibility: the input has a label, the chip list is a ul with an aria-label, and removal and addition are announced, for example with aria-live.

Use provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TagsInputComponent), multi: true, since the class is referenced inside its own decorator.

Test it with a host that has FormControl<string[]>: set the value, type a tag, press Enter, check control.value, and verify the error when the limit is exceeded.

typescript
import { Component, computed, forwardRef, input, signal } from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  ValidationErrors,
  Validator,
} from '@angular/forms';

@Component({
  selector: 'app-tags-input',
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TagsInputComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => TagsInputComponent), multi: true },
  ],
  template: `
    <ul aria-label="Tags">
      @for (tag of tags(); track tag) {
        <li>
          {{ tag }}
          <button type="button" [disabled]="disabled()" [attr.aria-label]="'Remove ' + tag" (click)="remove(tag)">x</button>
        </li>
      }
    </ul>
    <label>
      Add a tag
      <input
        #box
        [disabled]="disabled()"
        (keydown)="onKey($event, box)"
        (blur)="add(box.value); box.value = ''; onTouched()"
      />
    </label>
    <p aria-live="polite">{{ tags().length }} of {{ max() }} tags</p>
  `,
})
export class TagsInputComponent implements ControlValueAccessor, Validator {
  readonly max = input(5);

  readonly tags = signal<string[]>([]);
  readonly disabled = signal(false);
  readonly count = computed(() => this.tags().length);

  private onChange: (value: string[]) => void = () => {};
  onTouched: () => void = () => {};

  writeValue(value: string[] | null): void {
    this.tags.set(value ?? []);
  }

  registerOnChange(fn: (value: string[]) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled.set(isDisabled);
  }

  validate(_control: AbstractControl): ValidationErrors | null {
    const actual = this.count();
    return actual > this.max() ? { maxTags: { max: this.max(), actual } } : null;
  }

  onKey(event: KeyboardEvent, box: HTMLInputElement): void {
    if (event.key === 'Enter' || event.key === ',') {
      event.preventDefault();
      this.add(box.value);
      box.value = '';
    } else if (event.key === 'Backspace' && box.value === '' && this.tags().length > 0) {
      this.remove(this.tags()[this.tags().length - 1]);
    }
  }

  add(raw: string): void {
    const tag = raw.trim();
    if (!tag || this.tags().includes(tag)) {
      return;
    }
    this.update([...this.tags(), tag]);
  }

  remove(tag: string): void {
    this.update(this.tags().filter((t) => t !== tag));
  }

  private update(next: string[]): void {
    this.tags.set(next);
    this.onChange(next);
  }
}

Angular 20.3, strict template check passes, and a Karma test checks add, remove, and the validation error.

Key points

  • CVA moves values between the form and the component. `writeValue` must not call `onChange`.
  • `Validator` plus `NG_VALIDATORS` lets the control report its own errors.
  • Call `onValidatorChange` when a validator-related input changes.
  • Keyboard: Enter and comma add, Backspace removes. Label everything.

Common mistakes

  • Forgetting `multi: true` on either provider.
  • Mutating the tag array in place and passing the same reference to `onChange`.
  • Not calling `onTouched`, so the control is never marked touched.

Follow-ups

  • How would you add an async validator to a custom control?
  • How does the form know the validator inputs changed?
  • How would you support pasting a comma separated list?

Tips

  • Say that CVA and Validator are independent interfaces, and show you can combine them.
  • Describe keyboard handling and accessibility before you are asked.
  • Mention immutability of the emitted array.

Evaluation rubric

  • Implements all CVA methods without loops.
  • Registers and implements Validator correctly.
  • Handles keyboard and accessibility.
83.angular-0083Mediummid

How do you handle errors globally in Angular with ErrorHandler, provideBrowserGlobalErrorListeners and HTTP interceptors, and what should you show to users?

Angular sends uncaught errors from templates, event handlers and lifecycle hooks to the ErrorHandler service. Replace it with your own class to log to a monitoring service and show a friendly message. provideBrowserGlobalErrorListeners adds listeners for window errors and unhandled promise rejections. Handle expected HTTP failures separately in interceptors.

Full answer

There are two kinds of failures. Expected failures, such as a 404 from an API or a validation error, should be handled where they happen, with a message in the UI. Unexpected failures, such as a bug that throws in a template or a rejected promise nobody caught, need a global safety net.

ErrorHandler is the global hook. Angular calls handleError(error) for errors thrown in templates, event handlers, lifecycle hooks, and in effects. The default writes to the console. To replace it:

{ provide: ErrorHandler, useClass: GlobalErrorHandler }

In handleError you typically:

  • Normalise the error (some are wrapped, some are strings).
  • Send it to monitoring (Sentry, or your own endpoint) with context such as the route and app version. Do not send personal data, tokens, or form values.
  • Show a short, friendly message through a notification service, without technical details.
  • Avoid loops: if reporting fails, do not throw from the handler.

Which errors reach it: by default only errors Angular catches. provideBrowserGlobalErrorListeners() (added in Angular 20 and included in new project templates) registers error and unhandledrejection listeners on window and forwards those to ErrorHandler. This matters in zoneless apps, which have no zone to catch them.

HTTP errors: do not treat all HttpErrorResponse as crashes. An interceptor can map status codes to messages (401 goes to login, 403 shows "not allowed", 5xx shows "try again") and rethrow so the calling code can still react. Reserve ErrorHandler for the unexpected.

UI recovery: Angular has no built-in error boundary component. Keep errors local with catchError and a fallback state in the part of the page that failed, and offer a retry action.

typescript
// file: notifier.service.ts
import { Injectable, signal } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class Notifier {
  readonly message = signal<string | null>(null);

  show(text: string): void {
    this.message.set(text);
  }

  clear(): void {
    this.message.set(null);
  }
}

// file: global-error-handler.ts
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable, inject } from '@angular/core';
import { Router } from '@angular/router';
import { Notifier } from './notifier.service';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private readonly notifier = inject(Notifier);
  private readonly router = inject(Router);
  private readonly seen = new Set<string>();

  handleError(error: unknown): void {
    // HTTP errors are expected and are handled by interceptors and services.
    if (error instanceof HttpErrorResponse) {
      return;
    }
    const message = error instanceof Error ? error.message : String(error);
    if (this.seen.has(message)) {
      return; // do not report the same error many times
    }
    this.seen.add(message);

    try {
      // Replace with a monitoring client. Do not send tokens or form values.
      console.error('Unexpected error', { message, route: this.router.url });
    } catch {
      // Never throw from an error handler.
    }
    this.notifier.show('Something went wrong. Please try again.');
  }
}

// file: app.config.ts
import { ApplicationConfig, ErrorHandler, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { GlobalErrorHandler } from './global-error-handler';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter([]),
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
};

// file: banner.component.ts
import { Component, inject } from '@angular/core';
import { Notifier } from './notifier.service';

@Component({
  selector: 'app-error-banner',
  template: `
    @if (notifier.message(); as text) {
      <div role="alert">{{ text }} <button (click)="notifier.clear()">Dismiss</button></div>
    }
  `,
})
export class ErrorBannerComponent {
  protected readonly notifier = inject(Notifier);
}

Angular 20.3, strict template check passes, and a Karma test calls the handler. The reporter only logs to the console here. Replace it with a real monitoring client.

Key points

  • `ErrorHandler.handleError` is the global hook. Replace it with `{ provide: ErrorHandler, useClass: ... }`.
  • `provideBrowserGlobalErrorListeners()` forwards window errors and unhandled rejections to it.
  • Handle expected HTTP errors in interceptors and services, not in the global handler.
  • Log with context but without personal data. Show friendly messages.

Common mistakes

  • Sending form values or tokens to the monitoring service.
  • Throwing an error inside the error handler.
  • Showing raw error messages and stack traces to users.

Follow-ups

  • How would you avoid reporting the same error a thousand times?
  • How do you handle errors in a zoneless application?
  • How would you keep one failing widget from breaking the page?

Tips

  • Separate expected from unexpected errors. This is the key idea.
  • Mention privacy of logged data.
  • Say that you add local fallbacks, since there is no error boundary.

Evaluation rubric

  • Replaces ErrorHandler correctly.
  • Knows what reaches it and the Angular 20 listener provider.
  • Handles HTTP errors separately and considers privacy.
84.angular-0084Mediummid

Build an infinite scroll with an IntersectionObserver directive. How do you keep it SSR-safe, avoid duplicate loads and clean up?

Place a sentinel element after the list and observe it with an IntersectionObserver created inside afterNextRender, so it never runs on the server. When the sentinel becomes visible the directive emits an event, and the component loads the next page only if no request is running and more data exists. Disconnect the observer when the directive is destroyed.

Full answer

Infinite scroll appends content as the user nears the end of a list. A scroll listener that measures positions on every scroll event is wasteful. The IntersectionObserver API tells you when an element enters the viewport, with no layout reads in your code.

Design:

  1. A directive [appInView] on a sentinel element (an empty div after the list). It owns the observer.
  2. Create the observer in afterNextRender, because IntersectionObserver and layout do not exist on the server. rootMargin: '200px' fires a little before the sentinel is visible, so loading starts before the user hits the end.
  3. When isIntersecting is true, the directive emits inView.
  4. The component handles the output: if loading() or done(), return. Otherwise set loading, fetch the next page, append with [...old, ...next], and clear loading.
  5. DestroyRef.onDestroy(() => observer.disconnect()) cleans up.

Edge cases:

  • After new items are appended the sentinel moves down and leaves the viewport, so the observer fires again when it re-enters. If the first page is short and the sentinel stays visible, the observer will not fire again, because intersection did not change. Handle it by loading until the list fills the viewport, or by unobserving and observing again after each load.
  • Errors: show a retry button and do not loop.
  • End of data: hide the sentinel and show "No more results".
  • Accessibility: infinite scroll can trap keyboard users away from the footer. Offer a "Load more" button as an alternative, and announce new items with a polite live region.
  • Memory: for thousands of rows combine with virtual scroll or pagination.

A "Load more" button is the simplest accessible version, and many products use it instead of automatic loading.

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

@Directive({ selector: '[appInView]' })
export class InViewDirective {
  readonly rootMargin = input('200px');
  readonly inView = output<void>();

  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly destroyRef = inject(DestroyRef);

  constructor() {
    afterNextRender(() => {
      const observer = new IntersectionObserver(
        (entries) => {
          if (entries.some((e) => e.isIntersecting)) {
            this.inView.emit();
          }
        },
        { rootMargin: this.rootMargin() },
      );
      observer.observe(this.host.nativeElement);
      this.destroyRef.onDestroy(() => observer.disconnect());
    });
  }
}

@Component({
  selector: 'app-feed',
  imports: [InViewDirective],
  template: `
    <ul>
      @for (item of items(); track item) {
        <li>{{ item }}</li>
      }
    </ul>

    @if (done()) {
      <p>No more results</p>
    } @else {
      <div appInView (inView)="loadMore()" aria-hidden="true"></div>
      <button type="button" [disabled]="loading()" (click)="loadMore()">
        {{ loading() ? 'Loading...' : 'Load more' }}
      </button>
    }
    <p aria-live="polite">{{ items().length }} items loaded</p>
  `,
})
export class FeedComponent {
  readonly items = signal<string[]>([]);
  readonly loading = signal(false);
  readonly done = signal(false);

  constructor() {
    this.loadMore();
  }

  loadMore(): void {
    if (this.loading() || this.done()) {
      return;
    }
    this.loading.set(true);
    setTimeout(() => {
      const start = this.items().length;
      const next = Array.from({ length: 20 }, (_, i) => `Post ${start + i + 1}`);
      this.items.update((old) => [...old, ...next]);
      this.done.set(this.items().length >= 60);
      this.loading.set(false);
    }, 200);
  }
}

Angular 20.3, strict template check passes. The fake API returns 20 items per page up to 60.

Key points

  • `IntersectionObserver` on a sentinel replaces scroll listeners.
  • Create it in `afterNextRender` for SSR safety and disconnect on destroy.
  • Guard against duplicate loads with `loading` and `done` flags.
  • Provide a "Load more" button for accessibility and keyboard users.

Common mistakes

  • Creating the observer in the constructor and crashing during server rendering.
  • Not guarding against repeated loads while a request is running.
  • Forgetting that the observer does not fire again if the sentinel stays visible after loading.

Follow-ups

  • How would you re-trigger loading if the first page does not fill the screen?
  • How do you test code that depends on IntersectionObserver?
  • Why use `rootMargin`?

Tips

  • Say why not a scroll listener (layout reads on every event).
  • Mention the "sentinel stays visible" bug. It shows you have shipped one of these.
  • Offer the button alternative for accessibility.

Evaluation rubric

  • Creates and cleans up the observer safely.
  • Implements load guards and end-of-data states.
  • Considers accessibility and edge cases.
85.angular-0085Hardsenior

How do you design provide* functions for a library or feature, and how do you load runtime configuration before the app starts?

A provide function returns EnvironmentProviders built with makeEnvironmentProviders, so consumers add one call to their config. For runtime configuration, load a config file with provideAppInitializer before bootstrap completes and expose it through a service. This lets one build run in many environments, unlike fileReplacements, which bakes values in at build time.

Full answer

Modern Angular libraries and features expose a function such as provideRouter(...) or provideHttpClient(...), not a module with forRoot().

Writing a provide function:

  • Return EnvironmentProviders from makeEnvironmentProviders([...]). This type cannot be placed in a component's providers by mistake, which prevents a common error.
  • Take options as parameters, with defaults.
  • Support optional features with a features pattern: small functions (withLogging()) that return objects with providers, as provideHttpClient(withInterceptors(...)) does. Features keep the core small and tree-shakeable.
  • Use InjectionToken with a factory for defaults that work without any provider.

Configuration approaches:

  1. Build-time: fileReplacements in angular.json swaps environment.ts per configuration. Simple and fully typed, but you need one build per environment, and the same artifact cannot move from staging to production.
  2. Runtime: ship one build, and load /config.json (written by the deployment) at start-up. This follows the "build once, deploy many" rule and lets operations change API URLs without a rebuild.

Loading at start-up: provideAppInitializer(() => inject(ConfigService).load()) runs in an injection context before the app is considered started. If the function returns a Promise or an Observable, Angular waits for it. This replaces the older APP_INITIALIZER token with multi: true. Router initial navigation, and rendering, do not start until the work is done, so keep it fast and add a timeout. A failure blocks start-up, so decide on a fallback (default config, or an error page).

Rules: never put secrets in runtime config files (they are public). Validate the loaded object (a hand-written check or a schema library). Keep the config in a signal so features can read it with computed. Exposing it as a token (APP_CONFIG) with useFactory: () => inject(ConfigService).config() is another option, but it fails if read before loading, so the service approach with a clear error is safer.

typescript
// file: config.service.ts
import { EnvironmentProviders, Injectable, computed, inject, makeEnvironmentProviders, provideAppInitializer, signal } from '@angular/core';

export interface AppConfig {
  apiBaseUrl: string;
  features: Record<string, boolean>;
}

const DEFAULT_CONFIG: AppConfig = { apiBaseUrl: '/api', features: {} };

function isAppConfig(value: unknown): value is AppConfig {
  const v = value as Partial<AppConfig> | null;
  return typeof v === 'object' && v !== null && typeof v.apiBaseUrl === 'string' && typeof v.features === 'object';
}

@Injectable({ providedIn: 'root' })
export class ConfigService {
  private readonly state = signal<AppConfig | null>(null);

  readonly config = computed(() => {
    const value = this.state();
    if (!value) {
      throw new Error('Config is not loaded yet');
    }
    return value;
  });

  async load(url: string, timeoutMs = 3000): Promise<void> {
    try {
      const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
      const body: unknown = await response.json();
      if (!response.ok || !isAppConfig(body)) {
        throw new Error('Invalid config');
      }
      this.state.set(body);
    } catch {
      this.state.set(DEFAULT_CONFIG); // fallback so the app can still start
    }
  }
}

export interface ConfigFeature {
  url: string;
}

export function withConfigUrl(url: string): ConfigFeature {
  return { url };
}

export function provideAppConfig(...features: ConfigFeature[]): EnvironmentProviders {
  const url = features[0]?.url ?? '/config.json';
  return makeEnvironmentProviders([provideAppInitializer(() => inject(ConfigService).load(url))]);
}

// file: config.service.spec.ts
import { ApplicationInitStatus } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ConfigService, provideAppConfig, withConfigUrl } from './config.service';

describe('provideAppConfig', () => {
  afterEach(() => {
    (window.fetch as jasmine.Spy).and?.callThrough?.();
  });

  it('loads the config before the app is initialised', async () => {
    spyOn(window, 'fetch').and.resolveTo(
      new Response(JSON.stringify({ apiBaseUrl: 'https://api.example.com', features: { beta: true } })),
    );
    TestBed.configureTestingModule({ providers: [provideAppConfig(withConfigUrl('/config.json'))] });
    await TestBed.inject(ApplicationInitStatus).donePromise;

    expect(TestBed.inject(ConfigService).config().apiBaseUrl).toBe('https://api.example.com');
  });

  it('falls back to defaults when the request fails', async () => {
    spyOn(window, 'fetch').and.rejectWith(new Error('network down'));
    TestBed.configureTestingModule({ providers: [provideAppConfig()] });
    await TestBed.inject(ApplicationInitStatus).donePromise;

    expect(TestBed.inject(ConfigService).config().apiBaseUrl).toBe('/api');
  });
});

Angular 20.3, strict check passes, and a Karma spec runs the initializer against a stubbed `fetch` and checks the loaded value and the failure path.

Key points

  • Return `EnvironmentProviders` from `makeEnvironmentProviders`. Use feature functions for options.
  • Build-time `fileReplacements` is typed but needs a build per environment.
  • Runtime config with `provideAppInitializer` supports build once, deploy many.
  • Validate config, add a timeout and a fallback, and never store secrets in it.

Common mistakes

  • Putting secrets in `environment.ts` or `config.json`. Both are public.
  • Letting a slow config request delay the whole start-up with no timeout.
  • Reading the config before it loads, for example in a module-level constant.

Follow-ups

  • How does `provideAppInitializer` differ from `APP_INITIALIZER`?
  • How would you keep config loading from delaying the first paint with SSR?
  • How do you test a function that calls `provideAppInitializer`?

Tips

  • Contrast the two configuration styles, and say which you choose and why.
  • Mention `EnvironmentProviders` and what it protects against.
  • Say clearly that front-end config is never secret.

Evaluation rubric

  • Designs provide functions and features correctly.
  • Explains runtime versus build-time configuration with trade-offs.
  • Handles failure, validation, and security.
86.angular-0086Hardsenior

How do you protect an Angular app against CSRF, set up a Content Security Policy with nonces, and decide where to store auth tokens?

Angular's HttpClient reads an XSRF cookie and copies it into a header on mutating requests to your own origin, if your server issues the cookie and checks the header. CSP with a per-response nonce limits injected scripts and needs CSP_NONCE for Angular styles. Prefer HttpOnly cookies for sessions, and if you use bearer tokens, attach them only to your own API origin.

Full answer

Security in a single-page app has three separate topics.

CSRF (cross-site request forgery): a malicious site makes the user's browser send a request to your API, and the browser attaches cookies automatically. If you authenticate with cookies, you need protection:

  • Angular's built-in support is the double-submit cookie pattern. The server sets a cookie (default name XSRF-TOKEN, readable by JavaScript). For mutating requests (anything but GET and HEAD) to relative URLs or the same origin, HttpClient copies the cookie value into the X-XSRF-TOKEN header. The server compares them. Another site cannot read your cookie, so it cannot add the header.
  • Customise names with withXsrfConfiguration({ cookieName, headerName }), or disable it with withNoXsrfProtection() when you use tokens only.
  • Add SameSite=Lax or Strict on session cookies as a second layer. Angular does not add the header to requests to other origins.
  • If you authenticate with a bearer token in a header, the browser does not add it automatically, so classic CSRF does not apply. XSS becomes the main risk.

CSP (Content Security Policy): a response header that lists allowed sources for scripts and styles. Aim for script-src 'nonce-...' 'strict-dynamic' and no unsafe-inline. Angular adds inline styles at run time, so give it the nonce: put ngCspNonce="<nonce>" on the root element (the server sets a fresh random value per response) or provide CSP_NONCE. With the application builder you can also enable autoCsp in build options (v19+, experimental) to generate a hash-based policy.

Token storage:

  • Best: server-managed session or tokens in HttpOnly; Secure; SameSite cookies (BFF pattern). JavaScript cannot read them, so XSS cannot steal them, and you need CSRF protection.
  • If you must hold a token in JavaScript, keep it in memory (lost on refresh, refreshed silently), not in localStorage, which any injected script can read.
  • Use short-lived access tokens and refresh rotation.

Interceptor rule: attach the Authorization header only to your API origin. Sending it to every URL leaks tokens to third parties, such as analytics or image hosts.

Defence in depth: keep Angular's sanitisation on, never use bypassSecurityTrust* on user input, and avoid innerHTML with untrusted data (see the XSS item).

typescript
// file: security.config.ts
import { HttpInterceptorFn, provideHttpClient, withInterceptors, withXsrfConfiguration } from '@angular/common/http';
import { ApplicationConfig, CSP_NONCE } from '@angular/core';

export const API_ORIGIN = 'https://api.example.com';

let accessToken: string | null = null; // memory only: never localStorage
export function setAccessToken(token: string | null): void {
  accessToken = token;
}

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const isApi = req.url.startsWith(`${API_ORIGIN}/`);
  if (!isApi || !accessToken) {
    return next(req);
  }
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${accessToken}` } }));
};

function readNonce(): string | null {
  return document.querySelector('app-root')?.getAttribute('ngCspNonce') ?? null;
}

export const securityConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(
      withXsrfConfiguration({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }),
      withInterceptors([authInterceptor]),
    ),
    // Only needed if the server sends a nonce but you cannot use the ngCspNonce attribute.
    { provide: CSP_NONCE, useFactory: readNonce },
  ],
};

// file: security.config.spec.ts
import { HttpClient, provideHttpClient, withInterceptors, withXsrfConfiguration } from '@angular/common/http';
import { PlatformLocation } from '@angular/common';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { API_ORIGIN, authInterceptor, setAccessToken } from './security.config';

describe('http security', () => {
  let http: HttpClient;
  let backend: HttpTestingController;

  beforeEach(() => {
    document.cookie = 'XSRF-TOKEN=abc123; path=/';
    TestBed.configureTestingModule({
      providers: [
        provideHttpClient(withXsrfConfiguration({}), withInterceptors([authInterceptor])),
        provideHttpClientTesting(),
        // The test platform's mock location has no real origin (its href is "//"), and the XSRF
        // interceptor skips requests when it cannot work out the origin. Give it one.
        { provide: PlatformLocation, useValue: { href: 'http://localhost:4200/' } },
      ],
    });
    http = TestBed.inject(HttpClient);
    backend = TestBed.inject(HttpTestingController);
    setAccessToken('token-1');
  });

  afterEach(() => {
    document.cookie = 'XSRF-TOKEN=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
    setAccessToken(null);
    backend.verify();
  });

  it('adds the XSRF header to a same-origin POST', () => {
    http.post('/api/marks', {}).subscribe();
    const req = backend.expectOne('/api/marks');
    expect(req.request.headers.get('X-XSRF-TOKEN')).toBe('abc123');
    req.flush({});
  });

  it('does not add the XSRF header to a GET', () => {
    http.get('/api/marks').subscribe();
    const req = backend.expectOne('/api/marks');
    expect(req.request.headers.has('X-XSRF-TOKEN')).toBeFalse();
    req.flush({});
  });

  it('sends the bearer token only to the API origin', () => {
    http.get(`${API_ORIGIN}/marks`).subscribe();
    http.get('https://cdn.example.net/logo.png').subscribe();

    const api = backend.expectOne(`${API_ORIGIN}/marks`);
    const cdn = backend.expectOne('https://cdn.example.net/logo.png');
    expect(api.request.headers.get('Authorization')).toBe('Bearer token-1');
    expect(cdn.request.headers.has('Authorization')).toBeFalse();
    api.flush({});
    cdn.flush('');
  });
});

Angular 20.3, strict check passes, and a Karma spec in headless Chrome checks that the XSRF header is added for a same-origin POST and that the token goes only to the API origin.

Key points

  • Angular double-submit XSRF: cookie to header on mutating same-origin requests, checked by the server.
  • CSP with nonces and `strict-dynamic`. Give Angular the nonce for its styles.
  • Prefer `HttpOnly` cookies, or in-memory tokens. Avoid `localStorage` for tokens.
  • Send bearer tokens only to your own API origin.

Common mistakes

  • Disabling XSRF protection while using cookie sessions.
  • Using `unsafe-inline` in the CSP because Angular styles were blocked, instead of providing a nonce.
  • Adding the token header to every outgoing request, including third-party URLs.
  • Testing XSRF without a valid location origin, so the interceptor silently adds nothing and the test passes only for the wrong reason.

Follow-ups

  • Why does a bearer-token API not need CSRF protection, and what risk replaces it?
  • How would you rotate and revoke refresh tokens?
  • What is a backend-for-frontend, and how does it help?

Tips

  • Separate the three topics at the start. It shows structure.
  • Explain why the double-submit pattern works, in one sentence.
  • Name the trade-off of cookies versus in-memory tokens.

Evaluation rubric

  • Explains CSRF protection and Angular's built-in support correctly.
  • Describes CSP nonces and Angular's role.
  • Chooses token storage with reasons and scopes the interceptor.
87.angular-0087Hardsenior

What are component harnesses, why are they better than querying the DOM in tests, and how do you write your own?

A component harness is a class that wraps a component's DOM behind an API such as increment() or getValue(). Tests use that API, not CSS selectors, so internal markup can change without breaking tests. Angular Material ships harnesses for its components, and you write your own by extending ComponentHarness with a hostSelector.

Full answer

Tests that query the DOM directly (fixture.nativeElement.querySelector('.btn-primary')) break when markup or class names change, even if behaviour is the same. They also repeat the same selectors in many tests.

A harness puts those details in one class:

  • It extends ComponentHarness from @angular/cdk/testing.
  • It has a static hostSelector that finds the component's host element.
  • It defines locators in terms of the DOM with this.locatorFor('button.inc') and exposes methods in terms of behaviour: increment(), getValue().
  • Methods are asynchronous. The harness environment waits for change detection and pending work (fixture.whenStable) after each action, so you do not need fixture.detectChanges() or tick() for it.
  • A static with(options) method returns a HarnessPredicate to find a specific instance, for example the counter with a given label.

Using it in a test:

const loader = TestbedHarnessEnvironment.loader(fixture); const counter = await loader.getHarness(CounterHarness); await counter.increment(); expect(await counter.getValue()).toBe(1);

Benefits:

  • The same harness works with unit tests (TestbedHarnessEnvironment), and with end to end tests in Protractor-like environments through other HarnessEnvironment implementations.
  • Library authors ship harnesses with components (Angular Material does: MatButtonHarness, MatSelectHarness, MatDialogHarness). Your tests then do not depend on Material's internal DOM, so upgrades are safe.
  • Nested harnesses: a form-field harness can return the harness of the control inside it with getControl().

Limits: harnesses add an abstraction, so they pay off for shared components that many tests touch, not for a one-off component. For overlays (menus, dialogs), use documentRootLoader since the content lives outside the fixture.

typescript
// file: counter.component.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <span class="value" data-test="value">{{ count() }}</span>
    <button type="button" data-test="inc" (click)="count.set(count() + 1)">Add one</button>
    <button type="button" data-test="reset" (click)="count.set(0)">Reset</button>
  `,
})
export class CounterComponent {
  readonly count = signal(0);
}

// file: counter.harness.ts
import { BaseHarnessFilters, ComponentHarness, HarnessPredicate } from '@angular/cdk/testing';

export interface CounterHarnessFilters extends BaseHarnessFilters {
  minValue?: number;
}

export class CounterHarness extends ComponentHarness {
  static hostSelector = 'app-counter';

  private readonly value = this.locatorFor('[data-test="value"]');
  private readonly incButton = this.locatorFor('[data-test="inc"]');
  private readonly resetButton = this.locatorFor('[data-test="reset"]');

  static with(options: CounterHarnessFilters = {}): HarnessPredicate<CounterHarness> {
    return new HarnessPredicate(CounterHarness, options).addOption('minValue', options.minValue, async (harness, min) => {
      return (await harness.getValue()) >= min;
    });
  }

  async getValue(): Promise<number> {
    return Number(await (await this.value()).text());
  }

  async increment(): Promise<void> {
    await (await this.incButton()).click();
  }

  async reset(): Promise<void> {
    await (await this.resetButton()).click();
  }
}

// file: counter.component.spec.ts
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
import { CounterHarness } from './counter.harness';

@Component({
  selector: 'app-host',
  imports: [CounterComponent],
  template: `<app-counter /><app-counter />`,
})
class HostComponent {}

describe('CounterHarness', () => {
  let fixture: ComponentFixture<HostComponent>;

  beforeEach(() => {
    fixture = TestBed.createComponent(HostComponent);
  });

  it('increments and resets through the harness', async () => {
    const loader = TestbedHarnessEnvironment.loader(fixture);
    const counter = await loader.getHarness(CounterHarness);

    await counter.increment();
    await counter.increment();
    expect(await counter.getValue()).toBe(2);

    await counter.reset();
    expect(await counter.getValue()).toBe(0);
  });

  it('finds one of several counters with a predicate', async () => {
    const loader = TestbedHarnessEnvironment.loader(fixture);
    const [first] = await loader.getAllHarnesses(CounterHarness);
    await first.increment();

    const busy = await loader.getHarness(CounterHarness.with({ minValue: 1 }));
    expect(await busy.getValue()).toBe(1);
    expect((await loader.getAllHarnesses(CounterHarness)).length).toBe(2);
  });
});

Angular 20.3 with CDK 20.2. The spec was run in headless Chrome with `ng test`.

Key points

  • A harness hides DOM details behind a behaviour API, so refactors do not break tests.
  • Extend `ComponentHarness`, set `hostSelector`, use `locatorFor`, and return promises.
  • Auto-waits for stability. Use `TestbedHarnessEnvironment.loader(fixture)`.
  • Material ships harnesses. Use `documentRootLoader` for overlays.

Common mistakes

  • Forgetting to `await` harness calls, which makes assertions run too early.
  • Selecting by CSS classes used for styling inside the harness, instead of stable attributes such as `data-test`.
  • Writing a harness for a component that only one test uses.

Follow-ups

  • How do you find one of several harness instances with a predicate?
  • Where do the contents of a Material dialog live, and how do you test them?
  • When is querying the DOM directly still fine?

Tips

  • Show the before and after of one assertion. It makes the benefit clear.
  • Mention that Material and CDK ship harnesses for their own components.
  • Say that harness methods are async and auto-wait.

Evaluation rubric

  • Explains the problem harnesses solve.
  • Writes a harness with a host selector, locators, and methods.
  • Knows about predicates, overlays, and limits.
88.angular-0088Hardsenior

How do you test components that use signals, effects, timers and injected services, using mocks and fakeAsync correctly?

Set inputs with fixture.componentRef.setInput, flush effects with TestBed.tick (or fixture.detectChanges), replace services with fakes through providers, and control time with fakeAsync and tick. Test behaviour that a user would see, and keep one real integration test for each important flow.

Full answer

Test setup:

  • Provide fakes at the DI level: { provide: GradeService, useValue: fake }. A plain object with jasmine.createSpyObj or a small class is enough. Do not mock the component's own methods.
  • Set inputs through fixture.componentRef.setInput('name', value). This works with signal inputs, and it triggers change detection like a real parent. Assigning to the property does not work for signal inputs.
  • Read signals by calling them. Assert on the rendered DOM for behaviour that users see, and on signal values for logic.

Effects: an effect runs during change detection, not at the moment you set a signal. In tests call fixture.detectChanges() (or TestBed.tick(), which replaced TestBed.flushEffects() in v20) and then assert. A root effect created in a service needs TestBed.tick(). If the effect sets another signal, flush again. Prefer testing the visible result over testing that the effect ran.

Time: use fakeAsync and tick(ms) for setTimeout, debounceTime, and timer. flush() runs all pending timers. discardPeriodicTasks() stops interval. For real Promises use await fixture.whenStable(), or flushMicrotasks(). In zoneless apps and for new code, Jasmine's clock (jasmine.clock().install()) or async and await with whenStable can replace fakeAsync, since fakeAsync depends on zone.js.

HTTP: use provideHttpClientTesting() and HttpTestingController rather than spies on HttpClient, and call verify() after each test.

Habits that keep tests stable:

  • One behaviour per test, with names that read as a sentence.
  • Avoid testing private fields or implementation (call counts of internal methods).
  • Reset state: each test gets a fresh TestBed, so do not share mutable fixtures between tests.
  • Keep mocks honest: type them (Pick<GradeService, 'load'>) so that a changed signature breaks the test at compile time.
  • Do not assert on timing that depends on the real clock.
typescript
// file: grade-badge.component.ts
import { Component, computed, effect, inject, input, signal } from '@angular/core';

export class GradeService {
  passMark(): number {
    return 40;
  }
  save(_marks: number): void {}
}

@Component({
  selector: 'app-grade-badge',
  template: `<p data-test="label">{{ label() }}</p>`,
})
export class GradeBadgeComponent {
  private readonly grades = inject(GradeService);

  readonly marks = input.required<number>();
  readonly saved = signal<number | null>(null);

  readonly label = computed(() => (this.marks() >= this.grades.passMark() ? 'Pass' : 'Fail'));

  constructor() {
    effect((onCleanup) => {
      const value = this.marks();
      const timer = setTimeout(() => {
        this.grades.save(value);
        this.saved.set(value);
      }, 500);
      onCleanup(() => clearTimeout(timer));
    });
  }
}

// file: grade-badge.component.spec.ts
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { GradeBadgeComponent, GradeService } from './grade-badge.component';

describe('GradeBadgeComponent', () => {
  let fixture: ComponentFixture<GradeBadgeComponent>;
  let grades: jasmine.SpyObj<Pick<GradeService, 'passMark' | 'save'>>;

  beforeEach(() => {
    grades = jasmine.createSpyObj('GradeService', ['passMark', 'save']);
    grades.passMark.and.returnValue(40);
    TestBed.configureTestingModule({ providers: [{ provide: GradeService, useValue: grades }] });
    fixture = TestBed.createComponent(GradeBadgeComponent);
  });

  function label(): string {
    return fixture.nativeElement.querySelector('[data-test="label"]').textContent.trim();
  }

  it('shows Pass at or above the pass mark', () => {
    fixture.componentRef.setInput('marks', 40);
    fixture.detectChanges();
    expect(label()).toBe('Pass');
  });

  it('shows Fail below the pass mark and updates when the input changes', () => {
    fixture.componentRef.setInput('marks', 39);
    fixture.detectChanges();
    expect(label()).toBe('Fail');

    fixture.componentRef.setInput('marks', 80);
    fixture.detectChanges();
    expect(label()).toBe('Pass');
  });

  it('saves after a pause and cancels the earlier save when the input changes', fakeAsync(() => {
    fixture.componentRef.setInput('marks', 50);
    fixture.detectChanges();
    tick(300);

    fixture.componentRef.setInput('marks', 60);
    fixture.detectChanges();
    tick(499);
    expect(grades.save).not.toHaveBeenCalled();

    tick(1);
    expect(grades.save).toHaveBeenCalledOnceWith(60);
    expect(fixture.componentInstance.saved()).toBe(60);
  }));

  it('uses the mock pass mark', () => {
    grades.passMark.and.returnValue(75);
    fixture.componentRef.setInput('marks', 70);
    fixture.detectChanges();
    expect(label()).toBe('Fail');
    TestBed.tick(); // flushes pending root effects, none are left here
  });
});

Angular 20.3. The spec was run in headless Chrome with `ng test` and all four tests pass.

Key points

  • Provide fakes through DI. Type them against the real service.
  • `setInput` for signal inputs. `fixture.detectChanges()` or `TestBed.tick()` to flush effects.
  • `fakeAsync` with `tick` for timers. HTTP with `HttpTestingController`.
  • Assert on visible behaviour. Do not test private details.

Common mistakes

  • Assigning to a signal input property directly in the test, which fails.
  • Asserting right after `signal.set` without flushing the effect.
  • Forgetting `discardPeriodicTasks` or `flush`, leaving timers pending in `fakeAsync`.

Follow-ups

  • How would you test a component in a zoneless app?
  • How would you test a `resource` that loads from an API?
  • How do you decide between a unit test and an integration test?

Tips

  • Mention the v20 change from `flushEffects` to `tick`.
  • Talk about typing mocks. It shows maintenance thinking.
  • Describe what you do not test.

Evaluation rubric

  • Uses setInput, DI fakes, and effect flushing correctly.
  • Controls time and HTTP properly.
  • Shows good testing habits.
89.angular-0089Hardsenior

How do you move heavy computation off the main thread in Angular with a Web Worker, and how do you keep it type-safe and SSR-safe?

A Web Worker runs JavaScript on another thread, so heavy loops do not freeze the UI. Angular CLI bundles a worker created with new Worker(new URL('./x.worker', import.meta.url)). Communicate with typed postMessage messages, keep the work in a pure function you can unit test, and skip workers on the server.

Full answer

JavaScript on the main thread handles rendering, input and your code. A 300 ms loop makes the page unresponsive for 300 ms. Typical causes: parsing large files, sorting or filtering tens of thousands of rows, image processing, and cryptography.

How to use a worker in Angular:

  1. ng generate web-worker grade creates grade.worker.ts and a tsconfig.worker.json, and adds webWorkerTsConfig to the build options. The worker file starts with /// <reference lib="webworker" />.
  2. Create it with new Worker(new URL('./grade.worker', import.meta.url), { type: 'module' }). The builder recognises this pattern and bundles the worker separately.
  3. Send data with worker.postMessage(data), and receive results in worker.onmessage. Data is copied with the structured clone algorithm, so functions, DOM nodes and class instances with methods cannot be sent. Large ArrayBuffers can be transferred (postMessage(buf, [buf])) to avoid copying.
  4. Terminate with worker.terminate() when no longer needed, typically in DestroyRef.onDestroy.

Good structure:

  • Put the algorithm in a plain function (rankStudents) in its own file. The worker imports it, and unit tests call it directly without any worker.
  • Type the messages: a Request and a Response type shared by both sides. Include an id to match responses to requests when several run at once.
  • Wrap the worker in a service that exposes a Promise or a signal, and handles errors (onerror, onmessageerror).
  • Check typeof Worker !== 'undefined'. During server rendering there is no Worker, so fall back to running the function inline.

Limits: workers have no DOM and no access to Angular services. Messages have a cost, so a worker does not help for tiny tasks. A pool, or a library such as Comlink, helps with many calls. For work that must stay on the main thread, split it into chunks with scheduler.yield() or setTimeout.

typescript
// file: rank-students.ts
export interface Student {
  name: string;
  marks: number;
}

export interface RankRequest {
  id: number;
  students: Student[];
}

export interface RankResponse {
  id: number;
  ranked: Array<Student & { rank: number }>;
}

export function rankStudents(students: Student[]): Array<Student & { rank: number }> {
  const sorted = [...students].sort((a, b) => b.marks - a.marks || a.name.localeCompare(b.name));
  return sorted.map((s, i) => ({ ...s, rank: i + 1 }));
}

// file: rank.worker.ts
/// <reference lib="webworker" />
import { rankStudents, RankRequest, RankResponse } from './rank-students';

addEventListener('message', ({ data }: MessageEvent<RankRequest>) => {
  const response: RankResponse = { id: data.id, ranked: rankStudents(data.students) };
  postMessage(response);
});

// file: rank.service.ts
import { DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { RankRequest, RankResponse, Student, rankStudents } from './rank-students';

@Injectable({ providedIn: 'root' })
export class RankService {
  private nextId = 1;
  private readonly pending = new Map<number, (r: RankResponse['ranked']) => void>();
  private worker?: Worker;

  constructor() {
    if (isPlatformBrowser(inject(PLATFORM_ID)) && typeof Worker !== 'undefined') {
      this.worker = new Worker(new URL('./rank.worker', import.meta.url), { type: 'module' });
      this.worker.onmessage = ({ data }: MessageEvent<RankResponse>) => {
        this.pending.get(data.id)?.(data.ranked);
        this.pending.delete(data.id);
      };
      inject(DestroyRef).onDestroy(() => this.worker?.terminate());
    }
  }

  rank(students: Student[]): Promise<RankResponse['ranked']> {
    if (!this.worker) {
      return Promise.resolve(rankStudents(students)); // server or old browser
    }
    const id = this.nextId++;
    const request: RankRequest = { id, students };
    return new Promise((resolve) => {
      this.pending.set(id, resolve);
      this.worker!.postMessage(request);
    });
  }
}

// file: demo.ts
import { rankStudents } from './rank-students.ts';

const result = rankStudents([
  { name: 'Asha', marks: 82 },
  { name: 'Ravi', marks: 91 },
  { name: 'Meena', marks: 82 },
]);
console.log(result);

Angular 20.3. The pure function was run in Node twice with identical output. The service and worker files are type-checked (the worker with `lib: webworker`). The worker was also bundled by `ng build` as a separate chunk, and a Karma spec in headless Chrome ranked students through the real worker. `ng generate web-worker` sets up `tsconfig.worker.json` and the build option.

Key points

  • Workers run on another thread, so the UI stays responsive.
  • `new Worker(new URL('./x.worker', import.meta.url), { type: 'module' })` is bundled by the CLI.
  • Messages are copied. Use typed messages, ids, and transfer large buffers.
  • Keep the algorithm pure for testing. Fall back when `Worker` is missing (SSR).

Common mistakes

  • Trying to send functions or class instances and getting a clone error.
  • Not terminating workers, which leaks threads.
  • Using a worker for a task shorter than the message overhead.

Follow-ups

  • How would you handle cancellation of a long-running job?
  • How would you run several jobs in a pool?
  • What can a worker not access?

Tips

  • Start with a measured problem (a long task in the profiler), not with "use workers".
  • Mention structured clone limits and transferables.
  • Describe the SSR fallback.

Evaluation rubric

  • Knows the bundling pattern and the message model.
  • Designs a typed, testable, SSR-safe wrapper.
  • Understands limits and costs.
90.angular-0090Hardsenior

When would you choose micro-frontends for Angular, how can they be built, and what problems do they bring?

Micro-frontends split a large UI into independently built and deployed apps owned by separate teams, loaded into a shell at run time. In Angular this is usually done with Module Federation or Native Federation, with shared contracts and careful version management. They solve organisational scaling, not technical complexity, and bring cost in performance, consistency and operations.

Full answer

The reason to adopt micro-frontends is organisational: many teams need to release separately, on different schedules, without coordinating one big build. They are not a way to make a small app better. A modular monolith in a monorepo (with Nx or Angular workspaces and enforced boundaries) is simpler and enough for most teams.

Ways to build them:

  • Module Federation (webpack) and Native Federation (browser import maps, works with the esbuild builder): a shell loads a remote's entry file at run time and gets its routes or components. @angular-architects/native-federation is the common choice for the application builder.
  • Iframes: strong isolation, poor integration (routing, sizing, accessibility).
  • Web Components (Angular Elements): each remote exposes custom elements, so even different frameworks can coexist.
  • Build-time composition: separate libraries published as packages and assembled in one app. Teams still release together, which can be fine.

Design decisions:

  1. Granularity: split by business area (billing, courses), not by technical layer. Each remote owns a route prefix.
  2. Shared dependencies: the shell and remotes must share one copy of Angular, or you run two Angular instances. Federation config marks @angular/* as singletons with a version range. A major version mismatch breaks the page, so plan upgrades together or use a compatibility window.
  3. Contracts: a small shared package defines the interface between the shell and the remote (authentication state, navigation events, route data). Avoid sharing services with internal types.
  4. Routing: the shell owns the top-level router and loads each remote with loadChildren, which makes it lazy loaded.
  5. Resilience: a remote can be down. Load with a timeout and a fallback page.
  6. Consistency: shared design tokens or a component library keep the look the same, and accessibility needs one standard.
  7. Operations: independent pipelines, versioned remote entries, a manifest that the shell reads at run time (so a remote can be released without redeploying the shell), and contract tests.

Costs: more network requests, duplicated code when sharing is imperfect, harder local development and debugging, and more complex monitoring. Say clearly when you would not use them.

typescript
// file: contract.ts
import { InjectionToken, Signal } from '@angular/core';
import { Routes } from '@angular/router';

// Shared package: the only thing the shell and remotes both import.
export interface ShellApi {
  readonly userName: Signal<string | null>;
  navigate(path: string): void;
}

export const SHELL_API = new InjectionToken<ShellApi>('SHELL_API');

export interface RemoteEntry {
  routes: Routes;
}

// file: remote-loader.ts
import { Component } from '@angular/core';
import { Route, Routes } from '@angular/router';
import { RemoteEntry } from './contract';

@Component({
  selector: 'app-remote-unavailable',
  template: `<p role="alert">This section is not available right now. Please try again later.</p>`,
})
export class RemoteUnavailableComponent {}

const FALLBACK: Routes = [{ path: '**', component: RemoteUnavailableComponent }];

function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
  return new Promise<T>((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error('Remote timed out')), ms);
    promise.then(
      (value) => {
        clearTimeout(timer);
        resolve(value);
      },
      (error) => {
        clearTimeout(timer);
        reject(error);
      },
    );
  });
}

export function remoteRoute(path: string, load: () => Promise<RemoteEntry>, timeoutMs = 4000): Route {
  return {
    path,
    loadChildren: () =>
      withTimeout(load(), timeoutMs).then(
        (entry) => entry.routes,
        () => FALLBACK,
      ),
  };
}

// file: app.routes.ts
import { Routes } from '@angular/router';
import { RemoteEntry } from './contract';
import { remoteRoute } from './remote-loader';

// With Native Federation the loader is: loadRemoteModule('billing', './routes').
// A plain dynamic import of a URL is used here to keep the sample dependency free.
const BILLING_ENTRY = 'https://billing.example.com/entry.js';

export const routes: Routes = [
  remoteRoute('billing', () => import(/* @vite-ignore */ BILLING_ENTRY) as Promise<RemoteEntry>),
];

Angular 20.3, type-checked. The sample shows the shell side: a typed contract, a loader with timeout and fallback, and the routes. The federation plugin itself is not installed here, so the dynamic import of a real remote is not run.

Key points

  • Micro-frontends solve team scaling and independent releases, not technical problems.
  • Options: Module or Native Federation, iframes, Web Components, build-time packages.
  • Hard parts: shared singleton dependencies, contracts, consistent UX, and operations.
  • A modular monolith with enforced boundaries is often the better first choice.

Common mistakes

  • Adopting micro-frontends for a small team and paying the cost with no benefit.
  • Sharing Angular versions loosely, producing two copies of Angular on one page.
  • Sharing internal services across remotes, which couples them tightly.

Follow-ups

  • How would you upgrade Angular across the shell and ten remotes?
  • How do you share login state between the shell and a remote?
  • How would you detect a broken contract before release?

Tips

  • Open by saying what problem they solve, and when you would not use them.
  • Name the singleton shared dependency problem. Interviewers look for it.
  • Give an alternative (modular monolith).

Evaluation rubric

  • Gives clear reasons and counter-reasons.
  • Knows the technical options and their trade-offs.
  • Addresses sharing, contracts, resilience, and operations.
91.angular-0091Hardsenior

How would you structure a large Angular codebase so that many developers can work in it, and how do you enforce the boundaries?

Organise by feature, not by file type, and split code into layers such as feature, domain, UI and shared, with rules about who may import whom. Expose each library through one public API file, and enforce the rules in the lint step with a boundary check, so structure does not depend on code review alone.

Full answer

Folders by file type (components/, services/, pipes/) work for small apps. At scale a change to one feature touches five folders, and anything can import anything.

A layout that scales:

apps/shell/ app config, routes libs/ courses/ feature-list/ smart components, routes feature-detail/ data-access/ services, state, API calls ui/ presentational components util/ pure functions shared/ ui/ design system util/

Rules (based on the Nx guidance):

  1. Group by domain first (courses, billing), then by type of library (feature, data-access, ui, util).
  2. Allowed direction: feature can use data-access, ui and util. ui and util cannot use data-access or feature. data-access can use util. A domain should not reach into another domain's internals.
  3. Each library has one public API file (index.ts). Others import only from there, so internals can change freely. Do not export everything. An export is a promise.
  4. Lazy load features by route.
  5. Avoid cycles. Move shared code down a layer, or use an event or a contract.
  6. Keep shared small. A giant shared/ folder becomes a second monolith.

Enforcing rules: write them in tooling. In an Nx workspace use @nx/enforce-module-boundaries with tags; without Nx, use ESLint no-restricted-imports, eslint-plugin-boundaries, or dependency-cruiser. Run it in CI so a violating import fails the build. A small script can also check the rule, as in the sample.

Process around the structure: code owners per library (CODEOWNERS), generators for new libraries and components, affected-only builds and tests (Nx cache) so CI stays fast, and architecture decision records for rules.

Honest trade-off: more libraries mean more configuration. Start with folders and boundaries inside one app, and split into libraries when team size or build time requires it.

typescript
// file: check-boundaries.ts
type Layer = 'feature' | 'data-access' | 'ui' | 'util';

const ALLOWED: Record<Layer, Layer[]> = {
  feature: ['data-access', 'ui', 'util'],
  'data-access': ['util'],
  ui: ['util'],
  util: [],
};

interface SourceFile {
  path: string;
  content: string;
}

function parse(path: string): { domain: string; layer: Layer; internal: boolean } | null {
  const match = path.match(/libs\/([^/]+)\/(feature|data-access|ui|util)[^/]*\/(.*)$/);
  if (!match) {
    return null;
  }
  return { domain: match[1], layer: match[2] as Layer, internal: match[3] !== 'index.ts' };
}

export function check(files: SourceFile[]): string[] {
  const problems: string[] = [];
  for (const file of files) {
    const from = parse(file.path);
    if (!from) {
      continue;
    }
    for (const m of file.content.matchAll(/from '@school\/([^/']+)\/([^/']+)(\/[^']*)?'/g)) {
      const [, domain, layerName, deepPath] = m;
      const layer = layerName.replace(/-.*/, '') as Layer;
      const target = layerName.startsWith('data-access') ? 'data-access' : layer;
      if (deepPath) {
        problems.push(`${file.path}: deep import of ${m[0].slice(5)}, use the public API`);
      }
      if (domain !== from.domain && target !== 'ui' && target !== 'util') {
        problems.push(`${file.path}: ${from.domain} must not use ${domain}/${target}`);
      }
      if (domain === from.domain && !ALLOWED[from.layer].includes(target as Layer) && target !== from.layer) {
        problems.push(`${file.path}: ${from.layer} must not use ${target}`);
      }
    }
  }
  return problems;
}

const sample: SourceFile[] = [
  { path: 'libs/courses/feature-list/list.ts', content: `import { Api } from '@school/courses/data-access';` },
  { path: 'libs/courses/ui/card.ts', content: `import { Api } from '@school/courses/data-access';` },
  { path: 'libs/billing/feature-pay/pay.ts', content: `import { Course } from '@school/courses/feature-list';` },
  { path: 'libs/billing/feature-pay/pay2.ts', content: `import { x } from '@school/courses/data-access/internal/store';` },
];

const problems = check(sample);
console.log(problems.length === 0 ? 'No boundary problems' : problems.join('\n'));

Angular 20.3. The script is plain TypeScript run with Node 24 (type stripping) twice with identical output. It checks sample files held in memory, so it needs no project. In a real repository use ESLint or dependency-cruiser.

Key points

  • Group by domain, then by type: feature, data-access, ui, util.
  • Define who may import whom, and expose a public API per library.
  • Enforce with lint or a dependency checker in CI.
  • Keep shared small, avoid cycles, and add structure only as the team grows.

Common mistakes

  • A large shared folder that everything depends on.
  • Importing deep internal paths of another library instead of its public API.
  • Rules written in a wiki and not enforced by tools.

Follow-ups

  • How would you break a circular dependency between two features?
  • What belongs in `data-access` and what in `util`?
  • How do you keep CI fast in a large monorepo?

Tips

  • Show the layers as a small picture and state the direction of imports.
  • Say that rules must be automated.
  • Mention the cost of too many small libraries.

Evaluation rubric

  • Gives a clear structure with reasons.
  • Defines import rules and a public API.
  • Automates enforcement and discusses trade-offs.
92.angular-0092Hardsenior

How do you choose a state management approach in Angular: component signals, a service with signals, NgRx Store, SignalStore or the router and server cache?

Start with the smallest tool that works: local component state for UI details, a signal service for state shared by a few components, and the URL for state that should survive a refresh or be shareable. Add NgRx Store or SignalStore when many features share complex state, need strict traceability, or need dev tools and effects. Keep server data in a cache layer such as resource, not duplicated in the store.

Full answer

Think of state by where it lives and who needs it, not by tool.

Kinds of state:

  1. UI state (a dropdown is open, a tab is selected): component signals. Never put this in a global store.
  2. Form state: the forms API. Keep unsaved values local until submit.
  3. URL state (page number, filters, selected id): router params and query params. It gives deep links and back-button support for free.
  4. Server state (courses from the API): it has loading, error, staleness and refresh. Use resource/httpResource, a query library, or a dedicated service with caching. Copying it into a global store creates a second source of truth that goes stale.
  5. Shared client state (the shopping cart, an unsaved edit that spans several screens, user preferences): this is where store choices matter.

Options for shared client state:

  • Signal service (@Injectable with private signals, public asReadonly() and methods): the simplest option. Little code, no library, easy to test. It does not enforce structure, so rules live in the team's habits.
  • NgRx SignalStore: a structured signal store with state, computed values, methods and features (entities, hooks, dev tools). Less boilerplate than Store, and strong conventions per feature.
  • NgRx Store with effects: actions, reducers, selectors and effects. More boilerplate, but every change is a named action, giving time-travel debugging, a clear audit trail, and strong conventions in large teams. Best when many developers work on complex, strongly interrelated state and need the trace.
  • Other libraries (Akita, Elf, NGXS) are valid choices, but check maintenance and community support.

Decision signals: how many consumers, how complex the transitions are, whether you need an audit log or undo, team size and familiarity, and whether the state must be shared across lazy-loaded features.

Anti-patterns: one global store for everything, selectors that duplicate derived values, storing derived state instead of computing it, and mutating state. Start simple, and move up when a concrete pain appears, such as unclear update order or debugging difficulty.

typescript
// file: cart.store.ts
import { computed, signal } from '@angular/core';

export interface CartItem {
  id: number;
  name: string;
  price: number;
  qty: number;
}

export class CartStore {
  private readonly _items = signal<readonly CartItem[]>([]);

  readonly items = this._items.asReadonly();
  readonly count = computed(() => this._items().reduce((sum, i) => sum + i.qty, 0));
  readonly total = computed(() => this._items().reduce((sum, i) => sum + i.qty * i.price, 0));

  add(item: Omit<CartItem, 'qty'>): void {
    this._items.update((list) => {
      const existing = list.find((i) => i.id === item.id);
      return existing
        ? list.map((i) => (i.id === item.id ? { ...i, qty: i.qty + 1 } : i))
        : [...list, { ...item, qty: 1 }];
    });
  }

  remove(id: number): void {
    this._items.update((list) => list.filter((i) => i.id !== id));
  }
}

// file: demo.ts
import { CartStore } from './cart.store.ts';

const cart = new CartStore();
cart.add({ id: 1, name: 'Samosa', price: 15 });
cart.add({ id: 1, name: 'Samosa', price: 15 });
cart.add({ id: 2, name: 'Tea', price: 10 });
console.log(cart.count(), cart.total());
cart.remove(1);
console.log(cart.count(), cart.total());

Angular 20.3, type-checked. The sample is a minimal signal service for shared client state and is executed in Node (the signals API works without a browser), twice with identical output.

Key points

  • Classify state first: UI, form, URL, server, shared client.
  • URL and server state have better homes than a global store.
  • Signal service for simple sharing. SignalStore for structure. NgRx Store for strict traceability at scale.
  • Do not store derived data. Start simple and upgrade for a real reason.

Common mistakes

  • Putting everything in NgRx because it is "the standard".
  • Duplicating API data in a store and in a cache, so two copies disagree.
  • Storing values that could be computed from other state.

Follow-ups

  • How would you migrate a service with BehaviorSubjects to signals?
  • What would make you add NgRx Store to an app that uses a signal service?
  • How do you keep state when the user refreshes the page?

Tips

  • Start with the kinds of state. It shows you do not apply one tool everywhere.
  • Say what each option costs, not only what it gives.
  • Mention the URL as state. Many candidates forget it.

Evaluation rubric

  • Separates the kinds of state.
  • Compares options with honest trade-offs.
  • Gives clear criteria for upgrading.
93.angular-0093Hardsenior

How do you find and reduce what makes an Angular bundle large, using the esbuild application builder, budgets and the stats file?

The application builder (esbuild and Vite) is the default since Angular 17. Run ng build --stats-json, group the output by package to see what dominates, then fix the largest items: lazy load routes and @defer blocks, remove unused imports, avoid heavy libraries, and drop zone.js with zoneless mode. Budgets in angular.json fail the build when sizes grow.

Full answer

Start with measurement, not guesses.

The builder: @angular/build:application uses esbuild for bundling and Vite for the dev server. It produces hashed files for the browser, optional server and prerender output, and with --stats-json it writes stats.json, an esbuild metafile that lists each output file and how many bytes each input module contributed.

Analysis steps:

  1. ng build --stats-json. Read the console table: initial chunks (loaded before the app can start) and lazy chunks (loaded later). Initial size matters most.
  2. Open the stats file in a visualiser (the esbuild bundle size analyzer web page, source-map-explorer with source maps, or your own script as below). Group by package to see which dependency dominates.
  3. Fix the largest items first.

Common fixes:

  • Lazy load routes (loadComponent, loadChildren) and heavy parts of a page with @defer.
  • Import precisely: import { map } from 'rxjs' is tree-shaken, but a whole library imported from a barrel that has side effects may not be. Prefer libraries with ES module builds and sideEffects: false.
  • Replace heavy libraries (moment with date-fns or the Intl API, lodash with native methods or per-function imports).
  • Images: use NgOptimizedImage and modern formats. Fonts: subset them.
  • Zone.js is about 34 KiB of the polyfills in the sample build below. Zoneless mode (stable in 20.2) removes it.
  • Check 3rdpartylicenses.txt and the table for duplicated versions of a package.
  • Production configuration already minifies, tree-shakes, inlines critical CSS, and hashes names. Turn on optimization and avoid shipping source maps to users.

Budgets: angular.json configurations accept budgets with type (initial, anyComponentStyle, bundle, anyScript), maximumWarning and maximumError. The default project sets initial warning at 500 kB and error at 1 MB. Tighten them to your real numbers, so a pull request that adds 80 kB fails in CI with a message instead of passing unnoticed.

Do not forget runtime cost: size is only a proxy. Check Core Web Vitals (LCP, INP), use SSR or prerendering for first paint, and test on a mid-range phone.

typescript
// file: analyze-stats.mjs
import { readFileSync } from 'node:fs';

const statsPath = process.argv[2] ?? 'dist/my-app/stats.json';
const stats = JSON.parse(readFileSync(statsPath, 'utf8'));

function packageOf(file) {
  const marker = 'node_modules/';
  const at = file.lastIndexOf(marker);
  if (at === -1) {
    return 'your code';
  }
  const rest = file.slice(at + marker.length).split('/');
  return rest[0].startsWith('@') ? `${rest[0]}/${rest[1]}` : rest[0];
}

for (const [name, output] of Object.entries(stats.outputs)) {
  if (!name.endsWith('.js')) {
    continue;
  }
  const bytesByPackage = new Map();
  for (const [file, info] of Object.entries(output.inputs)) {
    const pkg = packageOf(file);
    bytesByPackage.set(pkg, (bytesByPackage.get(pkg) ?? 0) + info.bytesInOutput);
  }
  console.log(`${name} (${(output.bytes / 1024).toFixed(1)} KiB)`);
  [...bytesByPackage]
    .sort((a, b) => b[1] - a[1])
    .slice(0, 4)
    .forEach(([pkg, bytes]) => console.log(`  ${pkg.padEnd(24)} ${(bytes / 1024).toFixed(1)} KiB`));
}

// Typical output on a fresh project:
//   main-U464A3LU.js (208.1 KiB)
//     @angular/core            89.7 KiB
//     @angular/router          64.7 KiB
//     your code                17.9 KiB
//     rxjs                     16.7 KiB
//   polyfills-5CFQRCPP.js (33.8 KiB)
//     zone.js                  33.8 KiB

// file: angular.budgets.json
{
  "configurations": {
    "production": {
      "budgets": [
        { "type": "initial", "maximumWarning": "400kB", "maximumError": "600kB" },
        { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" },
        { "type": "bundle", "name": "admin", "maximumError": "150kB" }
      ],
      "outputHashing": "all"
    }
  }
}

Angular 20.3 with the application builder. The script was run in Node twice with identical output, against the `stats.json` from a real `ng build --stats-json` of a fresh CLI project (main chunk 208.1 KiB raw, polyfills 33.8 KiB, estimated transfer about 70 kB). The numbers in the sample output depend on the project, so run it on yours.

Key points

  • `ng build --stats-json` gives per-module sizes. Group by package and fix the largest first.
  • Lazy load routes and use `@defer`. Import precisely. Replace heavy libraries.
  • Zoneless mode removes zone.js from polyfills.
  • Budgets fail CI when size grows. Measure runtime metrics too.

Common mistakes

  • Optimising without measuring, so effort goes to small items.
  • Setting budgets so high that they never fail.
  • Looking only at total size and ignoring the initial chunk.

Follow-ups

  • What is the difference between the `initial` and `anyComponentStyle` budgets?
  • How does `@defer` change the chunks?
  • How would you find a library that was bundled twice?

Tips

  • Describe a loop: measure, fix the biggest, measure again.
  • Quote a real number from a build you ran.
  • Link bundle size to user metrics, not only to kilobytes.

Evaluation rubric

  • Knows the application builder and the stats file.
  • Lists effective fixes with reasons.
  • Uses budgets and runtime measurements.
94.angular-0094Hardsenior

How do you write custom RxJS operators, and how do you use groupBy with higher-order operators to process work per key in order?

A custom operator is a function that takes and returns an Observable transform, built by composing existing operators with pipe. It names a repeated pattern, such as turning a request stream into loading, success and error states. groupBy combined with mergeMap and concatMap runs work in parallel across keys and in order within each key.

Full answer

An operator is a function (source: Observable<T>) => Observable<R>. Most custom operators are just reusable pipe combinations:

export function withStatus<T>(): OperatorFunction<T, Status<T>> { return (source) => source.pipe( map((value) => ({ state: 'success', value })), catchError((error) => of({ state: 'error', error })), startWith({ state: 'loading' }), ); }

Guidelines:

  • Make it generic, and type input and output with OperatorFunction<In, Out> or MonoTypeOperatorFunction<T>.
  • Compose existing operators when possible. Writing a raw new Observable operator is rarely needed, and then you must handle unsubscribe, errors and completion yourself.
  • Keep operators pure: no hidden shared state between subscriptions. Create state inside the returned function (defer), so each subscription gets its own copy.
  • Name by intent (withStatus, pollUntil), and test with marble tests or fakeAsync.

Higher-order patterns in practice: a "higher-order observable" emits Observables. Flattening operators decide how inner streams combine: switchMap (latest wins), mergeMap (all in parallel), concatMap (one by one), exhaustMap (ignore while busy).

A common real problem: process events for many students at once, but keep the events of one student in order (for example, saving edits to one record). Use groupBy(event => event.studentId), which splits the stream into one group per key, then mergeMap(group => group.pipe(concatMap(save))). Different students run in parallel, and each student's saves run one after another. Without groupBy, a global concatMap is too slow, and a global mergeMap can reorder one student's saves.

Memory: groups stay open forever by default. For many keys, close idle groups with groupBy(key, { duration: group => group.pipe(debounceTime(...)) }), or the stream leaks.

typescript
// file: operators.ts
import { type Observable, type OperatorFunction, catchError, concatMap, delay, groupBy, map, mergeMap, of, startWith } from 'rxjs';

export type Status<T> =
  | { state: 'loading' }
  | { state: 'success'; value: T }
  | { state: 'error'; message: string };

export function withStatus<T>(): OperatorFunction<T, Status<T>> {
  return (source) =>
    source.pipe(
      map((value): Status<T> => ({ state: 'success', value })),
      catchError((error: Error) => of<Status<T>>({ state: 'error', message: error.message })),
      startWith<Status<T>>({ state: 'loading' }),
    );
}

export interface Edit {
  studentId: number;
  text: string;
  saveMs: number;
}

// Parallel across students, strictly ordered within one student.
export function savePerStudent(save: (edit: Edit) => Observable<string>): OperatorFunction<Edit, string> {
  return (source) =>
    source.pipe(
      groupBy((edit) => edit.studentId),
      mergeMap((group) => group.pipe(concatMap((edit) => save(edit)))),
    );
}

export const fakeSave = (edit: Edit): Observable<string> =>
  of(`saved ${edit.studentId}:${edit.text}`).pipe(delay(edit.saveMs));

// file: main.ts
import { from, throwError, toArray } from 'rxjs';
import { type Edit, fakeSave, savePerStudent, withStatus } from './operators.ts';

const edits: Edit[] = [
  { studentId: 1, text: 'a', saveMs: 60 },
  { studentId: 2, text: 'x', saveMs: 20 },
  { studentId: 1, text: 'b', saveMs: 10 },
  { studentId: 2, text: 'y', saveMs: 30 },
];

from(edits)
  .pipe(savePerStudent(fakeSave), toArray())
  .subscribe((results) => {
    console.log('order of completion', results);

    from(['ok']).pipe(withStatus()).pipe(toArray()).subscribe((s) => console.log('success path', JSON.stringify(s)));
    throwError(() => new Error('server down')).pipe(withStatus(), toArray()).subscribe((s) => console.log('error path', JSON.stringify(s)));
  });

RxJS 7.8, type-checked. The script runs in Node 24 and prints the same output on two runs. Timers use distinct delays, so the order does not depend on ties.

Key points

  • An operator is a function from Observable to Observable. Compose with `pipe`.
  • Use `defer` for per-subscription state. Type with `OperatorFunction`.
  • `switchMap`, `mergeMap`, `concatMap` and `exhaustMap` differ in how inner streams combine.
  • `groupBy` then `mergeMap` and `concatMap` gives parallel across keys, ordered within each key. Close idle groups.

Common mistakes

  • Keeping state in a closure shared by all subscribers of the operator.
  • Using a global `mergeMap` when order per key matters.
  • Never closing `groupBy` groups for an unbounded set of keys.

Follow-ups

  • How would you test this operator with marble tests?
  • What happens to an inner error inside `mergeMap` for the other groups?
  • How would you add a concurrency limit to `mergeMap`?

Tips

  • Show the problem that the operator solves first, then the code.
  • Explain the choice of flattening operator in one sentence each.
  • Mention the group lifetime. It is a common leak.

Evaluation rubric

  • Writes a typed, composable operator.
  • Chooses flattening operators correctly.
  • Handles per-key ordering and cleanup.
95.angular-0095Hardsenior

How do you build and publish a reusable Angular library, and what do public API design, peer dependencies and secondary entry points mean?

Angular libraries are built with ng-packagr (ng build for a library project) into a partial-Ivy package that each consuming app compiles again. Control the public API through one public-api.ts, declare Angular as a peer dependency, split optional features into secondary entry points, expose provide functions, and follow semantic versioning.

Full answer

Creating one: ng generate library my-ui creates a project in projects/my-ui with ng-package.json, package.json, and src/public-api.ts. ng build my-ui runs ng-packagr and writes to dist/my-ui. Publish that folder, not the source.

Key ideas:

  1. Partial compilation: the library is compiled to "partial Ivy" output, which is stable across Angular minor versions. The application's build links it to the exact Angular version. This is why a library built with Angular 19 works in 20 (within the supported range).
  2. Public API: only symbols exported from public-api.ts are available to users. Import paths into internals are blocked by the package exports field. Treat every export as a commitment: exporting less is safer.
  3. Peer dependencies: list @angular/core and @angular/common as peerDependencies with a range such as ^19.0.0 || ^20.0.0. Do not make them regular dependencies, or users get two copies of Angular and DI breaks. Put small runtime helpers in dependencies.
  4. Secondary entry points: a folder with its own ng-package.json and public-api.ts becomes my-ui/table. Users import my-ui/table, so unused parts are not bundled, and heavy optional dependencies stay optional.
  5. Standalone components and provide functions: export standalone components, directives and pipes, and provideMyUi(...) functions. Avoid requiring a module.
  6. Styling: use CSS custom properties for themes and ViewEncapsulation carefully, since consumers cannot easily override Emulated styles.
  7. Versioning: semantic versioning. Breaking a public signature is a major release. Use @deprecated notes for a migration period, and provide ng update schematics for big changes.
  8. Quality: compile with strict and strictTemplates, test with the harness approach, ship harnesses for components, document each public symbol, and test the built package in a real app (npm pack or ng build then link).

During development, path mappings in tsconfig.json let an app import the library source without building. Before release, build and test the real output, since problems appear only in the packaged form.

typescript
// file: public-api.ts
export { ButtonComponent } from './lib/button.component';
export { provideMyUi, withTheme } from './lib/provide-my-ui';
export type { MyUiConfig } from './lib/config';

// file: lib/config.ts
import { InjectionToken } from '@angular/core';

export interface MyUiConfig {
  theme: 'light' | 'dark';
}

export const MY_UI_CONFIG = new InjectionToken<MyUiConfig>('MY_UI_CONFIG', {
  factory: () => ({ theme: 'light' }),
});

// file: lib/provide-my-ui.ts
import { EnvironmentProviders, makeEnvironmentProviders } from '@angular/core';
import { MY_UI_CONFIG, MyUiConfig } from './config';

export type MyUiFeature = Partial<MyUiConfig>;

export function withTheme(theme: MyUiConfig['theme']): MyUiFeature {
  return { theme };
}

export function provideMyUi(...features: MyUiFeature[]): EnvironmentProviders {
  const config: MyUiConfig = Object.assign({ theme: 'light' } as MyUiConfig, ...features);
  return makeEnvironmentProviders([{ provide: MY_UI_CONFIG, useValue: config }]);
}

// file: lib/button.component.ts
import { Component, inject, input } from '@angular/core';
import { MY_UI_CONFIG } from './config';

@Component({
  selector: 'my-ui-button',
  template: `<button type="button" [class.dark]="theme === 'dark'"><ng-content /></button>`,
})
export class ButtonComponent {
  readonly disabled = input(false);
  protected readonly theme = inject(MY_UI_CONFIG).theme;
}

// file: package.json
{
  "name": "my-ui",
  "version": "1.0.0",
  "peerDependencies": {
    "@angular/common": "^19.0.0 || ^20.0.0",
    "@angular/core": "^19.0.0 || ^20.0.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "sideEffects": false
}

Angular 20.3, the TypeScript of the public API is type-checked. ng-packagr is not installed here, so the library build itself was not run. The JSON files are configuration examples.

Key points

  • `ng generate library` and `ng build` use ng-packagr. Publish `dist`, not source.
  • Partial Ivy output is linked by the consuming app.
  • One public API, Angular as a peer dependency, optional features as secondary entry points.
  • Semantic versioning, deprecation periods, and test the packaged output.

Common mistakes

  • Listing `@angular/core` under `dependencies`, causing two copies of Angular.
  • Exporting internals "for convenience" and then being unable to change them.
  • Testing only against library source, and missing packaging errors.

Follow-ups

  • Why is a library compiled in partial mode?
  • How would you support Angular 19 and 20 with one version?
  • How do you ship a theme that apps can customise?

Tips

  • Explain partial compilation in one sentence. It shows depth.
  • Mention peer dependencies and the two-copies problem.
  • Talk about the cost of every public export.

Evaluation rubric

  • Knows the build tool and output.
  • Designs the public API, entry points, and dependencies correctly.
  • Covers versioning and testing the package.
96.angular-0096Hardsenior

Implement an optimistic update for toggling a task as done. How do you roll back on failure and handle several requests in flight?

Update the local state immediately, send the request, and on failure restore the previous value of only that item and show an error. Keep the previous value for each request, use a version or request counter per item so a late response from an older request cannot overwrite newer state, and let the server response be the final truth.

Full answer

An optimistic update assumes success. The UI changes at once, so the app feels fast, and the app corrects itself if the request fails. It suits low-risk, high-success actions such as toggles, likes, and reordering. Do not use it for payments or actions with side effects the user must see confirmed.

Steps:

  1. Remember the previous value of the item.
  2. Apply the new value to the local signal immutably.
  3. Send the request.
  4. On success: optionally replace the item with the server's version (it may contain new fields such as updatedAt).
  5. On error: restore only that item to the remembered value, unless a newer change to the same item has happened since, and show a message with a retry option.

Concurrency problems:

  • Rapid toggling sends several requests. Responses can arrive out of order. Use a counter per item: each change gets a number, and a response or rollback applies only if its number is still the latest for that item.
  • Another approach is to serialise requests per item with concatMap (see the groupBy item), or to cancel the old request with switchMap when the new value supersedes it. For toggles the final value is what matters, so switchMap per item is natural, but the server may still have processed the cancelled request, so the server must be idempotent.
  • Roll back one item only, not the whole list snapshot, or you will undo unrelated changes made in the meantime.

Other points: do not rollback silently. Tell the user. Keep a visible "saving" or "failed" mark if the action may take long. Make the request idempotent (send the target value done: true, not "toggle"), so retries are safe. Test it with HttpTestingController for success, failure, and out-of-order responses.

typescript
// file: task.store.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, inject, signal } from '@angular/core';

export interface Task {
  id: number;
  title: string;
  done: boolean;
}

@Injectable({ providedIn: 'root' })
export class TaskStore {
  private readonly http = inject(HttpClient);
  private readonly versions = new Map<number, number>();

  readonly tasks = signal<Task[]>([
    { id: 1, title: 'Revise signals', done: false },
    { id: 2, title: 'Finish homework', done: false },
  ]);
  readonly error = signal<string | null>(null);

  setDone(id: number, done: boolean): void {
    const previous = this.tasks().find((t) => t.id === id);
    if (!previous) {
      return;
    }
    const version = (this.versions.get(id) ?? 0) + 1;
    this.versions.set(id, version);
    this.error.set(null);

    this.replace(id, { done });

    this.http.patch<Task>(`/api/tasks/${id}`, { done }).subscribe({
      next: (server) => {
        if (this.versions.get(id) === version) {
          this.replace(id, server); // server is the final truth for the latest request
        }
      },
      error: () => {
        if (this.versions.get(id) === version) {
          this.replace(id, { done: previous.done });
          this.error.set(`Could not update "${previous.title}". Please try again.`);
        }
      },
    });
  }

  private replace(id: number, changes: Partial<Task>): void {
    this.tasks.update((list) => list.map((t) => (t.id === id ? { ...t, ...changes } : t)));
  }
}

// file: task.store.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { TaskStore } from './task.store';

describe('TaskStore optimistic update', () => {
  let store: TaskStore;
  let backend: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
    store = TestBed.inject(TaskStore);
    backend = TestBed.inject(HttpTestingController);
  });

  afterEach(() => backend.verify());

  it('updates at once and keeps the server value on success', () => {
    store.setDone(1, true);
    expect(store.tasks()[0].done).toBeTrue();

    backend.expectOne('/api/tasks/1').flush({ id: 1, title: 'Revise signals', done: true });
    expect(store.tasks()[0].done).toBeTrue();
    expect(store.error()).toBeNull();
  });

  it('rolls back only that task on failure', () => {
    store.setDone(1, true);
    store.setDone(2, true);

    backend.expectOne('/api/tasks/1').flush('', { status: 500, statusText: 'Server Error' });
    backend.expectOne('/api/tasks/2').flush({ id: 2, title: 'Finish homework', done: true });

    expect(store.tasks()[0].done).toBeFalse();
    expect(store.tasks()[1].done).toBeTrue();
    expect(store.error()).toContain('Revise signals');
  });

  it('ignores a stale failure when a newer change exists', () => {
    store.setDone(1, true); // request A
    store.setDone(1, false); // request B (newer)

    const [a, b] = backend.match('/api/tasks/1');
    b.flush({ id: 1, title: 'Revise signals', done: false });
    a.flush('', { status: 500, statusText: 'Server Error' }); // late failure of A

    expect(store.tasks()[0].done).toBeFalse();
    expect(store.error()).toBeNull();
  });
});

Angular 20.3, strict check passes, and a Karma spec with `HttpTestingController` checks success, rollback, and a stale failure that must not roll back newer state.

Key points

  • Apply the change locally first, then send the request. Roll back only the affected item on error.
  • Track a version per item so late responses cannot overwrite newer state.
  • Send the target value (idempotent), not "toggle".
  • Tell the user about failures. Avoid optimistic updates for high-risk actions.

Common mistakes

  • Restoring a whole-list snapshot, which undoes other changes.
  • Sending "toggle" instead of the target value, so a retry flips it back.
  • Ignoring out-of-order responses.

Follow-ups

  • When would you choose pessimistic updates instead?
  • How would you handle the user going offline?
  • How is this different with a `resource`?

Tips

  • Start with when optimistic updates are suitable.
  • Describe the out-of-order problem before being asked.
  • Say "idempotent" and explain it with an example.

Evaluation rubric

  • Implements apply, send, and rollback correctly.
  • Handles concurrency with versions or cancellation.
  • Knows when the pattern fits.
97.angular-0097Hardsenior

Build a WebSocket stream in RxJS that reconnects with exponential backoff, resets after success and stops when the component is destroyed.

Wrap the connection in defer so every retry creates a new socket, use retry with a delay function for exponential backoff and resetOnSuccess so the count restarts after a good connection, and let the consumer's unsubscribe close the socket. Share the stream with shareReplay or share so several components use one connection.

Full answer

Real-time features (live results, notifications, chat) use a WebSocket. Connections drop on bad networks, laptop sleep, and server restarts, so reconnecting is part of the feature.

Design with RxJS:

  1. Source: RxJS webSocket(url) returns a WebSocketSubject. It connects when subscribed, emits incoming messages, and closes the socket on unsubscribe. An error or an unexpected close ends the stream with an error or a complete.
  2. Reconnect: retry resubscribes to its source on error. To get a new socket on each attempt, build the source with defer(() => webSocket(url)), since a closed WebSocketSubject cannot be reused in some cases.
  3. Backoff: retry({ delay: (error, attempt) => timer(min(base * 2 ** (attempt - 1), max)) }). Add random jitter in production so thousands of clients do not reconnect at the same moment.
  4. Reset: after a successful connection the attempt counter should return to 1, or a user who had five failures last week would wait the maximum delay today. retry({ resetOnSuccess: true }) resets the count when the source emits a value.
  5. Clean close: a complete from the server (a normal close) can also trigger repeat, if you want to reconnect, and an intentional close from the app is just unsubscribe.
  6. Sharing: share() makes one socket serve many subscribers, and closes it when the last one leaves. shareReplay({ bufferSize: 1, refCount: true }) also gives late subscribers the latest message.
  7. Component use: toSignal(stream$), or takeUntilDestroyed() with subscribe, which closes the socket when the component is destroyed.
  8. Connection state: expose a signal such as connected, via the openObserver and closeObserver options of webSocket, so the UI can show "reconnecting...". Heartbeats (a ping every 30 seconds with a timeout) detect half-open connections that the browser does not report.

Security: use wss://, authenticate with a short-lived ticket in the first message or in a cookie, not with a long-lived token in the URL, since URLs end up in logs.

typescript
// file: reconnect.ts
import { Observable, defer, retry, timer } from 'rxjs';

export interface ReconnectOptions {
  baseMs?: number;
  maxMs?: number;
  jitter?: boolean;
  onWait?: (attempt: number, waitMs: number) => void;
}

export function reconnecting<T>(connect: () => Observable<T>, options: ReconnectOptions = {}): Observable<T> {
  const { baseMs = 1000, maxMs = 30000, jitter = true, onWait } = options;
  return defer(connect).pipe(
    retry({
      resetOnSuccess: true,
      delay: (_error, attempt) => {
        const exp = Math.min(baseMs * 2 ** (attempt - 1), maxMs);
        const wait = jitter ? Math.round(exp / 2 + Math.random() * (exp / 2)) : exp;
        onWait?.(attempt, wait);
        return timer(wait);
      },
    }),
  );
}

// file: live-results.service.ts
import { Injectable, signal } from '@angular/core';
import { shareReplay } from 'rxjs';
import { webSocket } from 'rxjs/webSocket';
import { reconnecting } from './reconnect';

export interface ResultMessage {
  student: string;
  marks: number;
}

@Injectable({ providedIn: 'root' })
export class LiveResultsService {
  readonly connected = signal(false);

  readonly results$ = reconnecting<ResultMessage>(
    () =>
      webSocket<ResultMessage>({
        url: 'wss://example.com/results',
        openObserver: { next: () => this.connected.set(true) },
        closeObserver: { next: () => this.connected.set(false) },
      }),
    { baseMs: 1000, maxMs: 30000 },
  ).pipe(shareReplay({ bufferSize: 1, refCount: true }));
}

// file: main.ts
import { Observable, Subscriber } from 'rxjs';
import { reconnecting } from './reconnect.ts';

let attempts = 0;
const flakySource = (): Observable<string> =>
  new Observable((subscriber: Subscriber<string>) => {
    attempts++;
    const current = attempts;
    const timer = setTimeout(() => {
      if (current < 3) {
        subscriber.error(new Error(`connection ${current} dropped`));
      } else {
        subscriber.next(`message from connection ${current}`);
        subscriber.complete();
      }
    }, 5);
    return () => clearTimeout(timer);
  });

reconnecting(flakySource, { baseMs: 10, maxMs: 100, jitter: false, onWait: (n, ms) => console.log(`attempt ${n} failed, waiting ${ms} ms`) }).subscribe({
  next: (m) => console.log(m),
  complete: () => console.log('done after', attempts, 'connections'),
});

RxJS 7.8 and Angular 20.3. The `reconnecting` function is generic over its source. It was run in Node 24 against a fake source that fails twice and then emits, twice with the same output (delays 10, 20 ms). The `webSocket` usage in the Angular service is type-checked, but not run against a real server here.

Key points

  • `defer` makes a fresh socket for each attempt.
  • `retry` with a delay function gives exponential backoff. `resetOnSuccess` restarts the count after success. Add jitter.
  • `share` or `shareReplay` with `refCount` serve many consumers with one socket and close it when unused.
  • `takeUntilDestroyed` or `toSignal` handles cleanup. Add heartbeats and a connection state signal.

Common mistakes

  • Retrying immediately in a loop with no delay, flooding the server.
  • Reusing a closed socket for retry instead of creating a new one.
  • Putting a long-lived token in the WebSocket URL.

Follow-ups

  • How do you detect a half-open connection?
  • How would you resend messages the client tried to send while disconnected?
  • Why use `refCount: true` with `shareReplay`?

Tips

  • Explain why `defer` is needed. Many candidates miss it.
  • Name the reset problem (`resetOnSuccess`).
  • Mention jitter and heartbeats.

Evaluation rubric

  • Builds reconnect with backoff, reset, and cleanup.
  • Shares one connection correctly.
  • Considers state, heartbeats, and security.
98.angular-0098Hardsenior

Build a form from a JSON configuration, with validators and conditional fields. How do you keep it type-safe and maintainable?

Describe each field in a typed configuration (a discriminated union by type), build a FormGroup from it with a map of validator factories, render controls with @switch on the field type, and show conditional fields with a visibleWhen rule that adds or removes controls. Keep the config as data so it can come from a server, and test the builder as a pure function.

Full answer

Dynamic forms suit admin tools, surveys, and onboarding where fields change often or come from the back end. They trade type safety and flexibility of layout for speed of change, so use them where the form really is data.

Design:

  1. Typed configuration: a discriminated union such as { type: 'text' | 'number' | 'select' | 'checkbox'; key; label; required?; options?; minLength?; visibleWhen?: { key; equals } }. The compiler checks that a select has options.
  2. Builder: a pure function buildForm(fields) returns a FormGroup with one FormControl per field. A map of validator factories turns config (required, minLength, pattern) into Validators. Keeping it pure makes it easy to unit test.
  3. Rendering: a loop with @switch (field.type) renders the right input. Each control gets a label, a for and id pair, and error messages linked with aria-describedby. A generic FieldComponent per type keeps the template short.
  4. Conditional fields: a field with visibleWhen is shown only when another control has a value. Hidden controls should be disabled, so their validators do not block submit and they are excluded from getRawValue() filters. A valueChanges subscription (or a computed over toSignal(form.valueChanges)) toggles disable() and enable().
  5. Types: the form value is Record<string, unknown>, which is the cost of dynamic forms. Narrow at the boundary with a parsing function or a schema (Zod, Valibot) before sending to the API.
  6. Server config: validate the config itself on load, and version it. Never trust it to contain executable code. Validators come from your own map, never from strings evaluated at run time.

When not to use it: forms with complex layout, cross-field business rules, or custom UX are clearer as normal code. Often a hybrid is best: a generic renderer for simple sections and hand-written components for special fields.

typescript
// file: dynamic-form.ts
import { Component, input } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';

interface BaseField {
  key: string;
  label: string;
  required?: boolean;
  visibleWhen?: { key: string; equals: unknown };
}
export type Field =
  | (BaseField & { type: 'text'; minLength?: number })
  | (BaseField & { type: 'number'; min?: number })
  | (BaseField & { type: 'select'; options: string[] })
  | (BaseField & { type: 'checkbox' });

export function validatorsFor(field: Field): ValidatorFn[] {
  const list: ValidatorFn[] = [];
  if (field.required) {
    list.push(field.type === 'checkbox' ? Validators.requiredTrue : Validators.required);
  }
  if (field.type === 'text' && field.minLength) {
    list.push(Validators.minLength(field.minLength));
  }
  if (field.type === 'number' && field.min !== undefined) {
    list.push(Validators.min(field.min));
  }
  return list;
}

export function buildForm(fields: Field[]): FormGroup<Record<string, FormControl<unknown>>> {
  const controls: Record<string, FormControl<unknown>> = {};
  for (const field of fields) {
    const initial = field.type === 'checkbox' ? false : '';
    controls[field.key] = new FormControl<unknown>(initial, { nonNullable: true, validators: validatorsFor(field) });
  }
  const form = new FormGroup(controls);
  applyVisibility(form, fields);
  form.valueChanges.subscribe(() => applyVisibility(form, fields));
  return form;
}

function applyVisibility(form: FormGroup<Record<string, FormControl<unknown>>>, fields: Field[]): void {
  for (const field of fields) {
    if (!field.visibleWhen) {
      continue;
    }
    const control = form.controls[field.key];
    const visible = form.controls[field.visibleWhen.key]?.value === field.visibleWhen.equals;
    if (visible && control.disabled) {
      control.enable({ emitEvent: false });
    } else if (!visible && control.enabled) {
      control.disable({ emitEvent: false });
    }
  }
}

@Component({
  selector: 'app-dynamic-form',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submitted = form.getRawValue()">
      @for (field of fields(); track field.key) {
        @if (form.controls[field.key].enabled) {
          <div>
            <label [for]="field.key">{{ field.label }}</label>
            @switch (field.type) {
              @case ('select') {
                <select [id]="field.key" [formControlName]="field.key">
                  @for (option of optionsOf(field); track option) {
                    <option [value]="option">{{ option }}</option>
                  }
                </select>
              }
              @case ('checkbox') {
                <input type="checkbox" [id]="field.key" [formControlName]="field.key" />
              }
              @case ('number') {
                <input type="number" [id]="field.key" [formControlName]="field.key" />
              }
              @default {
                <input type="text" [id]="field.key" [formControlName]="field.key" />
              }
            }
            @if (form.controls[field.key].touched && form.controls[field.key].invalid) {
              <small role="alert">{{ field.label }} is not valid</small>
            }
          </div>
        }
      }
      <button type="submit" [disabled]="form.invalid">Submit</button>
    </form>
  `,
})
export class DynamicFormComponent {
  readonly fields = input.required<Field[]>();
  form = new FormGroup<Record<string, FormControl<unknown>>>({});
  submitted: unknown = null;

  ngOnInit(): void {
    this.form = buildForm(this.fields());
  }

  optionsOf(field: Field): string[] {
    return field.type === 'select' ? field.options : [];
  }
}

// file: dynamic-form.spec.ts
import { buildForm, Field } from './dynamic-form';

describe('buildForm', () => {
  const fields: Field[] = [
    { type: 'text', key: 'name', label: 'Name', required: true, minLength: 3 },
    { type: 'checkbox', key: 'hasMentor', label: 'Has a mentor' },
    { type: 'text', key: 'mentorName', label: 'Mentor name', required: true, visibleWhen: { key: 'hasMentor', equals: true } },
  ];

  it('applies validators from the configuration', () => {
    const form = buildForm(fields);
    form.controls['name'].setValue('Al');
    expect(form.controls['name'].errors?.['minlength']).toBeTruthy();
    form.controls['name'].setValue('Asha');
    expect(form.controls['name'].valid).toBeTrue();
  });

  it('disables a hidden field so it does not block the form', () => {
    const form = buildForm(fields);
    form.controls['name'].setValue('Asha');
    expect(form.controls['mentorName'].disabled).toBeTrue();
    expect(form.valid).toBeTrue();

    form.controls['hasMentor'].setValue(true);
    expect(form.controls['mentorName'].enabled).toBeTrue();
    expect(form.valid).toBeFalse();

    form.controls['mentorName'].setValue('Ravi');
    expect(form.valid).toBeTrue();
  });
});

Angular 20.3, strict template check passes, and a Karma spec tests the builder (validators and conditional disabling).

Key points

  • Describe fields as a typed discriminated union. Build the group in a pure function.
  • Map config to validators from a fixed set, never evaluate strings.
  • `@switch` renders by field type. Disable hidden conditional controls.
  • The value type is loose. Validate at the boundary. Use code for complex forms.

Common mistakes

  • Leaving hidden controls enabled, so their validators block submit.
  • Evaluating expressions from config with `eval`, which is a security hole.
  • Using dynamic forms for a form that never changes.

Follow-ups

  • How would you add a cross-field rule such as "end date after start date"?
  • How would you support nested groups and repeating sections with `FormArray`?
  • How do you provide accessible error messages for generated fields?

Tips

  • Start with when dynamic forms are the right choice.
  • Say that validators come from a closed set. It shows security thinking.
  • Mention the typing limit honestly.

Evaluation rubric

  • Builds a typed configuration and a pure builder.
  • Handles conditional fields and rendering correctly.
  • Covers accessibility, security, and trade-offs.
99.angular-0099Hardsenior

How do you read the incoming request, set the response status and headers, and avoid duplicate data fetching during server-side rendering?

In SSR, inject the REQUEST token to read headers and cookies for the current user, and RESPONSE_INIT to set the status and headers of the rendered page. HttpClient responses are copied to the browser through the HTTP transfer cache, and TransferState moves any other data, so the browser does not fetch it again. Never store per-user data in module-level variables on the server.

Full answer

Server rendering runs your Angular code in Node for each request. Three practical topics:

  1. Reading the request. Angular 20 exports REQUEST, REQUEST_CONTEXT and RESPONSE_INIT from @angular/core. inject(REQUEST, { optional: true }) is a standard web Request on the server and null in the browser. Use it to read cookies (theme, language), the Accept-Language header, or the URL. The result must be the same on both sides after hydration, or the browser shows a mismatch, so send server-derived values to the browser with TransferState or read the same cookie there.
  2. Setting the response. inject(RESPONSE_INIT, { optional: true }) is a mutable ResponseInit on the server. Set status (404 for a missing course, so search engines do not index a soft 404) and headers (Cache-Control). The router can also redirect with a RedirectCommand returned from a guard or resolver, which the server turns into a redirect response.
  3. Avoiding duplicate fetching. With provideClientHydration(withHttpTransferCache()) (included by default when you add SSR with the CLI), HttpClient GET responses made on the server are serialised into the page and reused by the browser's first requests with the same URL and parameters, so no second request is sent. For data not fetched through HttpClient, put it in TransferState: the server calls set(key, value), and the browser calls get(key, default).

Server-only rules:

  • Browser APIs (window, localStorage, document.cookie) do not exist on the server. Use afterNextRender, isPlatformBrowser, or the DOCUMENT token.
  • The server process serves many users. Anything stored in a module-level variable or a root-level singleton is shared between requests. Per-request data must live in services created for the request (the Angular platform makes one application per request), never in module scope. A cached user name in a global would leak between users.
  • Do not call your own public API URL from the server if an internal URL is faster. Use HttpClient with a relative URL, handled by an interceptor that prefixes the right base per platform.
  • Use PendingTasks for async work, so rendering waits for it.

Test SSR by viewing the page source (the HTML must contain the content), by disabling JavaScript, and by checking the response status with curl -I.

typescript
// file: ssr-helpers.ts
import { isPlatformServer } from '@angular/common';
import { DOCUMENT, PLATFORM_ID, REQUEST, RESPONSE_INIT, TransferState, inject, makeStateKey } from '@angular/core';
import { ResolveFn } from '@angular/router';

export function readCookie(name: string): string | null {
  const request = inject(REQUEST, { optional: true });
  const header = request ? (request.headers.get('cookie') ?? '') : inject(DOCUMENT).cookie;
  const match = header.split('; ').find((c) => c.startsWith(`${name}=`));
  return match ? decodeURIComponent(match.slice(name.length + 1)) : null;
}

export function setStatus(status: number, cacheControl?: string): void {
  const init = inject(RESPONSE_INIT, { optional: true });
  if (!init) {
    return; // running in the browser
  }
  init.status = status;
  if (cacheControl) {
    const headers = new Headers(init.headers);
    headers.set('Cache-Control', cacheControl);
    init.headers = headers;
  }
}

export interface Course {
  id: string;
  title: string;
}

const COURSE_KEY = makeStateKey<Course | null>('course');

export const courseResolver: ResolveFn<Course | null> = (route) => {
  const state = inject(TransferState);
  const id = route.paramMap.get('id') ?? '';

  if (state.hasKey(COURSE_KEY)) {
    const cached = state.get(COURSE_KEY, null);
    state.remove(COURSE_KEY); // use once, then fetch normally on later navigations
    return cached;
  }

  const found: Course | null = id === 'angular' ? { id, title: 'Angular for Beginners' } : null;
  if (isPlatformServer(inject(PLATFORM_ID))) {
    if (!found) {
      setStatus(404, 'no-store');
    }
    state.set(COURSE_KEY, found);
  }
  return found;
};

Angular 20.3, strict check passes. The server tokens and `TransferState` types are checked by the compiler, but the code was not run in a server here, so no request or response behaviour is claimed beyond the API shapes.

Key points

  • `REQUEST` gives the web Request on the server, and `RESPONSE_INIT` sets status and headers.
  • The HTTP transfer cache and `TransferState` avoid fetching again in the browser.
  • Browser-only APIs need `afterNextRender` or platform checks.
  • Never keep per-user data in module scope on the server.

Common mistakes

  • Returning a 200 status with a "not found" page.
  • Reading `localStorage` during server rendering, which throws.
  • Storing user data in a module-level variable, leaking it to other requests.

Follow-ups

  • How does the transfer cache decide which responses to reuse?
  • What causes a hydration mismatch, and how do you find it?
  • How would you set cache headers per route?

Tips

  • Mention the one-application-per-request rule. It is a security point.
  • Say that 404 pages must return a 404 status.
  • Know both transfer mechanisms: the HTTP cache and `TransferState`.

Evaluation rubric

  • Uses REQUEST and RESPONSE_INIT correctly.
  • Avoids duplicate fetching and understands transfer mechanisms.
  • Recognises server-only safety issues.
100.angular-0100Hardsenior

Write a reusable debounced signal utility. How do you handle timers, cleanup and the difference between a debounced signal and a debounced observable?

A debounced signal reads a source signal and updates its own value only after the source has been quiet for a set time. Implement it with an effect that starts a timer and uses the cleanup callback to cancel the previous timer, or use toObservable with debounceTime and toSignal. Test with fakeAsync and flush effects with detectChanges or TestBed.tick.

Full answer

Search boxes, filters and autosave need debouncing: wait until the user pauses before doing expensive work. With signals the source is a signal (query), and you want a second signal (debouncedQuery) that follows it after a delay.

Approach 1: effect with cleanup. The effect reads the source, schedules a setTimeout to set the output, and registers a cleanup function that clears the timer. When the source changes before the timer fires, Angular runs the cleanup first (cancelling the old timer), then runs the effect again (starting a new timer). Only the final value reaches the output. Need an injection context (it creates an effect), and an initial value for the first read.

Approach 2: RxJS interop: toSignal(toObservable(source).pipe(debounceTime(300)), { initialValue }). It is short and gives access to all operators (distinctUntilChanged, switchMap). Both functions need an injection context. Note that toObservable also uses an effect, so values pass through change detection first.

Which to choose: the effect version has no RxJS dependency and is very small, but it only debounces. If the next step is an HTTP call, with cancellation, use the RxJS version, or feed the debounced signal into resource or httpResource as a params source, which cancels stale requests for you.

Details that matter:

  • Equality: set the output only when the value is different (signals do this by default for primitives).
  • Cleanup on destroy: effects are destroyed with their injection context, and the cleanup callback also runs then, so the pending timer does not fire on a destroyed component.
  • Writing to a signal: here the write happens in a timer callback, outside the reactive context. Since Angular 19, writing signals inside effects is allowed anyway (the old allowSignalWrites option is no longer needed), but a write inside the effect body can cause extra runs, so prefer computed or linkedSignal for derived values.
  • SSR: a setTimeout on the server delays nothing important, but pending timers can keep the process busy, so avoid long delays on the server.

Test it: use fakeAsync, set the source, call TestBed.tick() to flush the effect, tick(ms) to advance time, and assert the output.

typescript
// file: debounced.ts
import { Injector, Signal, assertInInjectionContext, effect, inject, signal, untracked } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime } from 'rxjs';

export function debounced<T>(source: Signal<T>, ms: number, injector?: Injector): Signal<T> {
  if (!injector) {
    assertInInjectionContext(debounced);
  }
  const output = signal(untracked(source));
  effect(
    (onCleanup) => {
      const value = source();
      const timer = setTimeout(() => output.set(value), ms);
      onCleanup(() => clearTimeout(timer));
    },
    { injector: injector ?? inject(Injector) },
  );
  return output.asReadonly();
}

export function debouncedWithRxjs<T>(source: Signal<T>, ms: number): Signal<T> {
  return toSignal(toObservable(source).pipe(debounceTime(ms)), { initialValue: untracked(source) });
}

// file: search-box.component.ts
import { Component, signal } from '@angular/core';
import { debounced } from './debounced';

@Component({
  selector: 'app-search-box',
  template: `
    <input aria-label="Search" [value]="query()" (input)="query.set($any($event.target).value)" />
    <p>Searching for: {{ term() }}</p>
  `,
})
export class SearchBoxComponent {
  readonly query = signal('');
  readonly term = debounced(this.query, 300);
}

// file: debounced.spec.ts
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { signal } from '@angular/core';
import { debounced } from './debounced';

describe('debounced', () => {
  it('emits only the last value after the pause', fakeAsync(() => {
    const query = signal('');
    const term = TestBed.runInInjectionContext(() => debounced(query, 300));
    TestBed.tick();

    query.set('a');
    TestBed.tick();
    tick(100);
    query.set('an');
    TestBed.tick();
    tick(100);
    query.set('ang');
    TestBed.tick();

    tick(299);
    expect(term()).toBe('');
    tick(1);
    expect(term()).toBe('ang');
  }));

  it('clears the pending timer when destroyed', fakeAsync(() => {
    const query = signal('');
    const term = TestBed.runInInjectionContext(() => debounced(query, 300));
    TestBed.tick();

    query.set('x');
    TestBed.tick();
    TestBed.resetTestingModule(); // destroys the injector and the effect
    tick(300);

    expect(term()).toBe('');
  }));
});

Angular 20.3, type-checked, and a Karma spec using `fakeAsync` and `TestBed.tick` checks that only the last value is emitted after the pause, and that the timer is cleared when the component is destroyed.

Key points

  • Effect plus `setTimeout` plus cleanup gives a debounced signal. The cleanup cancels the previous timer.
  • `toSignal(toObservable(s).pipe(debounceTime(ms)))` is the RxJS alternative with more operators.
  • Needs an injection context. Feed the result into `resource` for cancellation of stale requests.
  • Test with `fakeAsync`, `TestBed.tick`, and `tick`.

Common mistakes

  • Not cancelling the previous timer, so every keystroke produces an update.
  • Calling the utility outside an injection context.
  • Debouncing and then ignoring cancellation of the HTTP request that follows.

Follow-ups

  • When is writing a signal inside an effect a bad idea, and what would you use instead?
  • How would you add a "leading edge" option?
  • How does `resource` cancel a stale request?

Tips

  • Show both versions and say when you pick each.
  • Explain the cleanup callback order in one sentence.
  • Mention testing with `fakeAsync`.

Evaluation rubric

  • Implements a correct, cleaned-up debounce.
  • Compares with the RxJS approach.
  • Tests time-based behaviour properly.