← Interview prep

Angular interview questions

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

195 questions · Page 3 of 10

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

Page 3 of 10

Questions 41–60 of 195 · 0 of 20 on this page marked learned

41.angular-0041Hardsenior

How does Angular's injector hierarchy work, and how do inject() options (self, skipSelf, optional, host), viewProviders and runInInjectionContext behave?

Angular has two injector trees. The environment injector tree (root, route and module level) and the element injector tree (components and directives in the DOM structure). A lookup starts at the element injector, walks up the elements, then moves to the environment injectors. Options such as self, skipSelf, optional, and host restrict the walk, and runInInjectionContext lets plain functions call inject().

Full answer

When code asks for a token, Angular first checks the element injector of the current component or directive, then each parent element up to the root of the view, and then the environment injectors: route-level injectors for routes with providers, then the root injector, then the platform injector. The first match wins. If nothing matches, an error (NullInjectorError) is thrown, unless optional: true is set.

Where providers are placed:

  • providers on a component or directive: available to the component, its view, and its projected content children.
  • viewProviders on a component: available only to the component's own view children, not to projected content. Useful for hiding an implementation detail from content that users project in.
  • providedIn: 'root' or ApplicationConfig.providers: the root environment injector, one instance.
  • Route providers: a new environment injector for that route tree.

Options for inject(Token, { ... }) (or the older @Self, @SkipSelf, @Optional, @Host decorators):

  • optional: true: return null instead of throwing.
  • self: true: only look at this element's own injector.
  • skipSelf: true: start looking at the parent, which is how a component can find its own parent instance of the same type, such as a nested menu.
  • host: true: stop the search at the host element of the current component view.

runInInjectionContext(injector, fn) runs fn in a context where inject() is allowed. Use it for helper functions or a test. The EnvironmentInjector lets you do this outside a constructor. If you call inject() in a random method, Angular throws NG0203.

Edge case: a service provided at component level has the same lifetime as the component. Any service that must be shared across components must be provided higher up.

typescript
import {
  Component,
  EnvironmentInjector,
  Injectable,
  inject,
  runInInjectionContext,
  signal,
} from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-tab-group',
  template: `<ng-content />`,
})
export class TabGroupComponent {
  readonly active = signal('');
}

@Component({
  selector: 'app-tab',
  template: `<button (click)="select()">{{ name }}</button>`,
})
export class TabComponent {
  name = 'Tab';
  // Found through the element injector. optional: true allows use outside a group.
  private readonly group = inject(TabGroupComponent, { optional: true });

  select(): void {
    this.group?.active.set(this.name);
  }
}

@Injectable()
export class MenuState {
  // Looks for a MenuState on a parent element, skipping this component's own.
  readonly parent = inject(MenuState, { skipSelf: true, optional: true });

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

@Component({
  selector: 'app-menu',
  providers: [MenuState],
  template: `<p>Menu depth {{ state.depth() }}</p><ng-content />`,
})
export class MenuComponent {
  protected readonly state = inject(MenuState);
}

@Injectable({ providedIn: 'root' })
export class Helper {
  private readonly env = inject(EnvironmentInjector);

  showUrlLater(): string {
    // inject() is only allowed in an injection context, so open one on purpose.
    return runInInjectionContext(this.env, () => inject(Router).url);
  }
}

Angular 20.3, strict template check passes. The `TabComponent` finds its parent group through the element injector. `showUrlLater` is a helper that needs `runInInjectionContext` because it is called outside a constructor.

Key points

  • Two trees: element injectors (components, directives) and environment injectors (route, root, platform).
  • `viewProviders` hide a provider from projected content; `providers` do not.
  • `self`, `skipSelf`, `optional`, and `host` change where the lookup starts and stops.
  • `runInInjectionContext` makes `inject()` work in helper functions.

Common mistakes

  • Calling `inject()` inside an event handler and getting NG0203.
  • Providing a service in both root and a component and unknowingly working with two different instances.
  • Forgetting `optional: true` in a directive that may be used outside its parent, so it throws a NullInjectorError.

Follow-ups

  • What is the difference between `providers` and `viewProviders`?
  • How can a nested tree node get its parent node?
  • How would you override a root provider for one route only?

Tips

  • Explain the lookup order before the options. Everything else follows from it.
  • Use the nested menu or tab-group example for `skipSelf` and `optional`.
  • Mention the NG0203 error as something you have seen.

Evaluation rubric

  • Describes both injector trees and lookup order.
  • Uses inject options correctly.
  • Knows viewProviders and runInInjectionContext.
42.angular-0042Hardsenior

How do you create components dynamically in Angular using ViewContainerRef, NgComponentOutlet, and the createComponent bindings?

Use ViewContainerRef.createComponent to insert a component at runtime and set its inputs with ref.setInput, or use NgComponentOutlet in a template for simpler cases. The standalone createComponent function with an EnvironmentInjector creates components outside any container, and Angular 20 adds inputBinding, outputBinding and twoWayBinding helpers to wire them up.

Full answer

Sometimes the component type is not known at build time: a dashboard of user-chosen widgets, a modal service, a plugin screen, a toast. Angular offers three tools.

  1. NgComponentOutlet in a template: <ng-container [ngComponentOutlet]="widget()" [ngComponentOutletInputs]="{ title: 'Marks' }" />. This is the easiest option when the template can decide. It supports inputs and a custom injector, and handles destroy for you.

  2. ViewContainerRef.createComponent(Type): gives a ComponentRef. Get a container with viewChild('host', { read: ViewContainerRef }) on an ng-container or div. Then:

    • ref.setInput('message', 'Saved') sets inputs (works with signal inputs, and triggers OnPush updates).
    • ref.instance.closed.subscribe(...) listens to an output().
    • ref.destroy() removes it. Destroying the container, or its host component, also destroys the children.
  3. The standalone createComponent(Type, { environmentInjector, hostElement }) plus ApplicationRef.attachView(ref.hostView) creates a component outside any template. This is the approach for overlays that attach to document.body (the CDK Overlay does something similar).

Angular 20 adds declarative bindings: createComponent(Type, { bindings: [inputBinding('title', () => this.title()), outputBinding('closed', () => this.close())] }). These keep inputs reactive to signals, so you do not need to call setInput repeatedly. twoWayBinding is also available.

Lazy loading plus dynamic creation is a common pairing: const { ChartComponent } = await import('./chart.component') before createComponent. The component code is only downloaded when needed.

Points to watch: always destroy what you create (a modal opened 100 times must not leave 100 components), pass an injector when the dynamic component needs parent-scoped services, and prefer @defer or control flow when the set of components is known in advance.

typescript
import { NgComponentOutlet } from '@angular/common';
import {
  Component,
  ComponentRef,
  ViewContainerRef,
  input,
  inputBinding,
  output,
  outputBinding,
  signal,
  viewChild,
} from '@angular/core';

@Component({
  selector: 'app-alert',
  template: `
    <p>{{ message() }} <button (click)="closed.emit()">Close</button></p>
  `,
})
export class AlertComponent {
  message = input.required<string>();
  closed = output<void>();
}

@Component({
  selector: 'app-toast-host',
  imports: [NgComponentOutlet],
  template: `
    <button (click)="show('Saved')">Show with setInput</button>
    <button (click)="showWithBindings()">Show with bindings</button>
    <ng-container #host />

    <ng-container
      [ngComponentOutlet]="alertType"
      [ngComponentOutletInputs]="{ message: 'Static outlet' }"
    />
  `,
})
export class ToastHostComponent {
  readonly alertType = AlertComponent;
  private readonly host = viewChild.required('host', { read: ViewContainerRef });
  private readonly text = signal('Reactive text');

  show(message: string): void {
    const ref: ComponentRef<AlertComponent> = this.host().createComponent(AlertComponent);
    ref.setInput('message', message);
    ref.instance.closed.subscribe(() => ref.destroy());
  }

  showWithBindings(): void {
    const ref: ComponentRef<AlertComponent> = this.host().createComponent(AlertComponent, {
      bindings: [
        inputBinding('message', this.text),
        outputBinding('closed', () => ref.destroy()),
      ],
    });
  }
}

Angular 20.3, strict template check passes. `inputBinding` and `outputBinding` were added in Angular 20.0.

Key points

  • `NgComponentOutlet` for template-driven cases; `ViewContainerRef.createComponent` for code-driven ones.
  • `setInput` keeps signal inputs and OnPush working. Outputs are listened to through `instance`.
  • Standalone `createComponent` plus `ApplicationRef.attachView` supports overlays.
  • Angular 20 `inputBinding` and `outputBinding` make dynamic wiring declarative.

Common mistakes

  • Assigning `ref.instance.message = ...` for a signal input. It is read-only. Use `setInput`.
  • Forgetting to destroy dynamic components, leaking memory and DOM nodes.
  • Reaching for dynamic creation when `@switch` with fixed components would be simpler.

Follow-ups

  • How do you pass a custom injector to a dynamic component?
  • How would you build a simple modal service?
  • How does lazy loading combine with dynamic creation?

Tips

  • Start with the three tools and when each fits. This shows judgement.
  • Mention cleanup before the interviewer asks.
  • Say that known component sets should use `@switch` or `@defer`, and dynamic creation is for open-ended cases.

Evaluation rubric

  • Names several creation approaches with trade-offs.
  • Uses setInput and handles outputs and cleanup.
  • Knows the newer binding helpers.
43.angular-0043Hardsenior

How do you test services that call HttpClient, functional guards, and routing behaviour in Angular?

Use provideHttpClient with provideHttpClientTesting and the HttpTestingController to assert requests and flush fake responses, and call verify() after each test. Test functional guards through the router with RouterTestingHarness, or call them inside TestBed.runInInjectionContext. Fake only what is slow or external.

Full answer

Testing with HTTP. Provide the real HttpClient together with a testing backend: provideHttpClient() and provideHttpClientTesting() (the old HttpClientTestingModule is legacy). In a test:

  1. Call the service method and subscribe.
  2. const req = http.expectOne('/api/courses') finds the pending request and fails if there is none or more than one.
  3. Assert on req.request.method, headers, params, or body.
  4. req.flush(data) answers it. req.flush('x', { status: 500, statusText: 'Server Error' }) simulates an error. req.error(new ProgressEvent('error')) simulates a network failure.
  5. In afterEach, http.verify() checks that no unexpected request is left over.

Because interceptors are part of provideHttpClient, you test them the same way: add withInterceptors([...]) and check the headers on the captured request.

Testing a functional guard. Two options. A unit test runs the function in an injection context: TestBed.runInInjectionContext(() => authGuard(route, state)). An integration test is more realistic. RouterTestingHarness.create() gives a harness, and await harness.navigateByUrl('/admin') performs a real navigation with the real guard. Then assert on router.url or the rendered component with harness.routeNativeElement. The integration style also catches wiring mistakes in the route config.

General principles for a senior answer:

  • Fake the boundary (HTTP, storage, time), not your own services.
  • Prefer the test pyramid: many small unit tests, fewer integration tests, and a few end-to-end tests with Playwright or Cypress.
  • Control time with fakeAsync and tick, or with the Jasmine clock, so tests are quick and not flaky.
  • Do not test the framework (that @if works). Test your decisions.
  • Run tests in CI, and keep them fast enough that people run them locally.
typescript
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Component, Injectable, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CanActivateFn, Router, provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { Observable } from 'rxjs';

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

@Injectable({ providedIn: 'root' })
export class CourseApi {
  private readonly http = inject(HttpClient);

  list(): Observable<Course[]> {
    return this.http.get<Course[]>('/api/courses', { params: { page: 1 } });
  }
}

@Injectable({ providedIn: 'root' })
export class Session {
  isAdmin(): boolean {
    return false;
  }
}

export const adminGuard: CanActivateFn = () =>
  inject(Session).isAdmin() ? true : inject(Router).createUrlTree(['/login']);

@Component({ selector: 'app-page', template: `<p>page</p>` })
class PageComponent {}

describe('CourseApi', () => {
  let http: HttpTestingController;
  let api: CourseApi;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
    http = TestBed.inject(HttpTestingController);
    api = TestBed.inject(CourseApi);
  });

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

  it('requests page 1 and returns the courses', () => {
    let result: Course[] | undefined;
    api.list().subscribe((courses) => (result = courses));

    const req = http.expectOne((r) => r.url === '/api/courses');
    expect(req.request.method).toBe('GET');
    expect(req.request.params.get('page')).toBe('1');
    req.flush([{ id: 1, title: 'Angular' }]);

    expect(result).toEqual([{ id: 1, title: 'Angular' }]);
  });

  it('surfaces a server error to the caller', () => {
    let status = 0;
    api.list().subscribe({ error: (e) => (status = e.status) });

    http.expectOne((r) => r.url === '/api/courses').flush('boom', { status: 500, statusText: 'Server Error' });

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

describe('adminGuard', () => {
  it('redirects a visitor to /login', async () => {
    TestBed.configureTestingModule({
      providers: [
        provideRouter([
          { path: 'admin', component: PageComponent, canActivate: [adminGuard] },
          { path: 'login', component: PageComponent },
        ]),
        { provide: Session, useValue: { isAdmin: () => false } },
      ],
    });

    const harness = await RouterTestingHarness.create();
    await harness.navigateByUrl('/admin');

    expect(TestBed.inject(Router).url).toBe('/login');
  });
});

Angular 20.3 with Jasmine. Type-checked in strict mode and run with `ng test` (Karma, headless Chrome): all three specs pass.

Key points

  • `provideHttpClient()` plus `provideHttpClientTesting()` plus `HttpTestingController`; always call `verify()`.
  • `expectOne`, then assert on the request, then `flush` data or an error.
  • Test guards through `RouterTestingHarness` for realism, or `runInInjectionContext` for unit speed.
  • Fake boundaries and control time to avoid flaky tests.

Common mistakes

  • Forgetting `verify()`, so extra or missing requests go unnoticed.
  • Testing a guard only as a function and never checking that it is attached to the route.
  • Using real timers or real network calls in unit tests.

Follow-ups

  • How would you test an interceptor that retries on failure?
  • When would you pick an end-to-end test over a harness test?
  • How do you test a component that uses `@defer`?

Tips

  • Describe the testing layers you use and why. It shows engineering judgement.
  • Say you fake only boundaries. Over-mocking is a common weakness.
  • Mention `RouterTestingHarness` by name. It is the modern router test tool.

Evaluation rubric

  • Uses HttpTestingController correctly with verify.
  • Can test guards in unit and integration style.
  • Shows testing strategy awareness.
44.angular-0044Hardsenior

Which router features help in a large Angular application: canMatch, route-level providers, title handling, navigation error handling and view transitions?

canMatch lets the router choose between routes (or skip lazy code) by a runtime condition such as a feature flag or role. Route-level providers create scoped services for a route tree. withViewTransitions animates page changes with the browser API, and withNavigationErrorHandler centralises failed navigations. Together they structure large apps without extra libraries.

Full answer

In a small app the route list is a flat table. In a large one it carries architecture decisions.

canMatch. A normal guard (canActivate) runs after the router has matched a route. A canMatch guard runs while matching. If it returns false, the router acts as if the route did not exist and tries the next route with the same path. Two uses follow:

  • Feature flags and roles: serve NewCheckoutComponent to users with a flag and the old one to everybody else, on the same URL.
  • Security of the bundle: for a lazy route, a failing canMatch means the code chunk is never downloaded.

Route-level providers. A route can declare providers: [CheckoutDraft]. The router creates an environment injector for that route and its children. State lives as long as the user is inside the area. When the user leaves, the service is destroyed. This is a clean way to scope state without global stores.

Titles. Set title: 'Courses' or a resolver function on each route, and a custom TitleStrategy for a common format such as "Courses | Schoolabe". It improves accessibility, because screen readers announce the title on navigation.

View transitions. withViewTransitions() uses the browser's View Transition API for animated page changes. Browsers without support fall back to no animation. Use the onViewTransitionCreated hook to adjust it.

Errors. withNavigationErrorHandler(handler) receives failures such as a lazy chunk that did not load or a resolver that threw. It can log, show a message, or return a RedirectCommand to go elsewhere. Without it, the error goes to the global error handler.

Other settings: withInMemoryScrolling restores scroll position and handles anchors, withComponentInputBinding binds route data to inputs, and withRouterConfig changes behaviour such as onSameUrlNavigation: 'reload'.

typescript
import { Component, Injectable, inject, signal } from '@angular/core';
import {
  CanMatchFn,
  NavigationError,
  RedirectCommand,
  Router,
  Routes,
  provideRouter,
  withComponentInputBinding,
  withInMemoryScrolling,
  withNavigationErrorHandler,
  withViewTransitions,
} from '@angular/router';
import { ApplicationConfig } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class FlagService {
  private readonly on = signal(new Set<string>(['newCheckout']));

  isOn(flag: string): boolean {
    return this.on().has(flag);
  }
}

export const requireFlag =
  (flag: string): CanMatchFn =>
  () =>
    inject(FlagService).isOn(flag);

@Injectable()
export class CheckoutDraft {
  readonly items = signal<string[]>([]);
}

@Component({ selector: 'app-new-checkout', template: `<p>New checkout</p>` })
export class NewCheckoutComponent {
  readonly draft = inject(CheckoutDraft);
}

@Component({ selector: 'app-old-checkout', template: `<p>Old checkout</p>` })
export class OldCheckoutComponent {}

@Component({ selector: 'app-error-page', template: `<p>Something went wrong</p>` })
export class ErrorPageComponent {}

export const routes: Routes = [
  {
    path: 'checkout',
    title: 'Checkout',
    canMatch: [requireFlag('newCheckout')],
    providers: [CheckoutDraft], // one draft per visit to this route tree
    component: NewCheckoutComponent,
  },
  // Same path: used when the flag is off, because canMatch above returned false.
  { path: 'checkout', title: 'Checkout', component: OldCheckoutComponent },
  { path: 'error', component: ErrorPageComponent },
];

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withComponentInputBinding(),
      withViewTransitions(),
      withInMemoryScrolling({ scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled' }),
      withNavigationErrorHandler((error: NavigationError) => {
        console.error('Navigation failed', error.url, error.error);
        return new RedirectCommand(inject(Router).parseUrl('/error'));
      }),
    ),
  ],
};

Angular 20.3, type-checked. The flag service is a plain class here. In a real app it would read remote configuration.

Key points

  • `canMatch` runs during matching, can choose between routes on one path, and can prevent lazy chunk downloads.
  • Route `providers` scope services to a route tree.
  • `title` plus a `TitleStrategy` gives consistent page titles.
  • `withViewTransitions`, `withNavigationErrorHandler`, and `withInMemoryScrolling` are one-line router features.

Common mistakes

  • Using `canActivate` for feature flags, which still downloads the lazy chunk and leaves no fallback route.
  • Putting route-scoped state in the root injector, so it never resets.
  • Forgetting that the order of routes matters when `canMatch` falls through to the next one.

Follow-ups

  • How does `canMatch` differ from `canActivate` for a lazy route?
  • How would you animate only some navigations with view transitions?
  • When is a route-level provider better than a root service?

Tips

  • Lead with `canMatch` versus `canActivate`. It is the most common senior routing question.
  • Tie each feature to a real need: flags, scoped state, accessibility, error recovery.
  • Mention title handling for accessibility. Many candidates forget it.

Evaluation rubric

  • Explains canMatch correctly, including lazy code behaviour.
  • Understands scoped providers.
  • Knows the router feature functions.
45.angular-0045Hardsenior

How do you handle errors in RxJS streams with catchError and retry, and what do shareReplay and its refCount option do?

An error ends an Observable, so catchError must sit where it can recover without killing the outer stream, usually inside the flattening operator. retry can resubscribe with a count and a delay function for backoff. shareReplay shares one execution between subscribers and replays the last value, and refCount lets it stop the source when nobody listens.

Full answer

In RxJS an error is terminal. After error, the stream emits nothing more. This has a big consequence for long-lived streams such as a search box.

Where to put catchError: on the inner Observable. If you write search$.pipe(switchMap(q => http.get(q)), catchError(...)), one failed request ends the whole search stream and the box stops working. Writing search$.pipe(switchMap(q => http.get(q).pipe(catchError(() => of([]))))) handles the error and keeps the outer stream alive. The example below shows both: the inner version gives 1, -1, 3, and the outer version stops at 1, -1.

Retry. retry(3) resubscribes immediately, which can hammer a failing server. Use the config form: retry({ count: 3, delay: (error, attempt) => timer(2 ** (attempt - 1) * 100) }). This waits 100 ms, 200 ms, then 400 ms (exponential backoff). Only retry errors that make sense to retry (network errors, status 503), not a 400 or 401, and only for requests that are safe to repeat (GET, or idempotent calls).

Sharing. A cold Observable such as http.get(...) runs again for every subscriber. If two parts of the page subscribe, two requests go out. shareReplay({ bufferSize: 1, refCount: true }) runs the source once, caches the last value for late subscribers, and with refCount: true unsubscribes from the source when the last subscriber leaves. Without refCount the source subscription can stay alive (a possible leak for infinite sources). share() shares without replaying, and connectable/Subject are lower-level tools.

Also useful: finalize for cleanup that runs on complete, error, or unsubscribe; tap({ error }) for logging without changing the stream; and throwError(() => err) to rethrow after logging.

typescript
import {
  catchError,
  concatMap,
  defer,
  finalize,
  from,
  lastValueFrom,
  of,
  retry,
  shareReplay,
  throwError,
  timer,
  toArray,
} from 'rxjs';

// 1. Retry with backoff: fails twice, then succeeds.
let attempts = 0;
const flaky$ = defer(() => {
  attempts++;
  return attempts < 3 ? throwError(() => new Error('network down')) : of('data loaded');
});

const withRetry$ = flaky$.pipe(
  retry({ count: 3, delay: (_error, attempt) => timer(10 * 2 ** (attempt - 1)) }),
);
console.log('1.', await lastValueFrom(withRetry$), 'after', attempts, 'attempts');

// 2. Inner catchError keeps the outer stream alive; outer catchError ends it.
const mayFail = (n: number) => (n === 2 ? throwError(() => new Error('bad ' + n)) : of(n));

const inner = await lastValueFrom(
  from([1, 2, 3]).pipe(
    concatMap((n) => mayFail(n).pipe(catchError(() => of(-1)))),
    toArray(),
  ),
);
const outer = await lastValueFrom(
  from([1, 2, 3]).pipe(
    concatMap((n) => mayFail(n)),
    catchError(() => of(-1)),
    toArray(),
  ),
);
console.log('2. inner catchError:', inner); // [ 1, -1, 3 ]
console.log('2. outer catchError:', outer); // [ 1, -1 ]

// 3. Sharing one execution between two subscribers.
let calls = 0;
const source$ = defer(() => {
  calls++;
  return of('response');
});
const shared$ = source$.pipe(shareReplay({ bufferSize: 1, refCount: true }));

await lastValueFrom(source$);
await lastValueFrom(source$);
console.log('3. calls without sharing:', calls); // 2

calls = 0;
await lastValueFrom(shared$);
await lastValueFrom(shared$);
console.log('3. calls with shareReplay:', calls); // 1

// 4. finalize runs on completion.
await lastValueFrom(of('x').pipe(finalize(() => console.log('4. cleanup done'))));

Tested with RxJS 7 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), run twice with identical output. Delays are 10 ms and 20 ms so the script finishes quickly.

Key points

  • An error terminates the stream, so put `catchError` inside `switchMap` or `mergeMap`.
  • `retry` takes `{ count, delay }`; use backoff and retry only safe, transient failures.
  • `shareReplay({ bufferSize: 1, refCount: true })` makes one execution and replays the latest value.
  • `finalize` runs on complete, error, and unsubscribe.

Common mistakes

  • Placing `catchError` on the outer stream of an event source, which silently ends it after the first error.
  • Retrying immediately and forever, which turns a small outage into a bigger one.
  • Using `shareReplay(1)` without `refCount` on a long-lived source, which keeps it running.

Follow-ups

  • Which HTTP errors would you retry, and which would you not?
  • What is the difference between `share()` and `shareReplay()`?
  • How would you show an error message but still keep the stream alive?

Tips

  • Show the inner versus outer `catchError` difference with numbers. It proves understanding.
  • Mention idempotency when talking about retry.
  • Name `refCount`. Many candidates only know `shareReplay(1)`.

Evaluation rubric

  • Explains terminal errors and catchError placement.
  • Writes a retry with backoff and limits.
  • Explains shareReplay and refCount.
46.angular-0046Hardsenior

What are the most common Angular mistakes in real projects, including ExpressionChangedAfterItHasBeenChecked, template function calls, nested subscribes and mutation, and how do you fix them?

The usual problems are state changed during change detection (NG0100), heavy functions called from templates, subscribe inside subscribe, mutating inputs of OnPush components, missing cleanup, and missing track keys. Each has a direct fix with computed, switchMap, immutable updates, takeUntilDestroyed or toSignal, and a stable track expression.

Full answer

These come up in code reviews again and again.

  1. ExpressionChangedAfterItHasBeenChecked (NG0100). In development mode Angular checks twice. If a value used in a template changes between the two passes, it throws. Typical cause: a child changes parent state in ngAfterViewInit or ngOnInit, after the parent was already rendered. Fix: change the data flow (the parent owns the state and passes it down, or the child emits an event), compute values with computed, or move the change into a later task. Not a fix: hiding the error with setTimeout without understanding the cause, or detectChanges() calls.

  2. Heavy function calls in templates. {{ getTotal() }} runs on every change detection pass. Use a computed signal or a pure pipe.

  3. Nested subscribes. A subscribe inside a subscribe creates callback pyramids, leaks, and race conditions. Use switchMap, concatMap, or forkJoin.

  4. Mutation. Pushing into an array or editing an object that an OnPush child received. The view does not update. Create a new array or object, or use signal update with spread syntax.

  5. Missing cleanup. Subscribing to interval, valueChanges, or router events without takeUntilDestroyed, the async pipe, or toSignal.

  6. Missing or poor track in @for (or trackBy in the legacy *ngFor), causing DOM rebuilds.

  7. Putting logic in components that belongs in services, making testing hard.

  8. Using any. It removes the checks that the typed forms, typed HTTP, and strict templates provide. Turn on strict and strictTemplates.

  9. Importing a whole module or a large library for one function, which inflates the bundle.

  10. Not handling HTTP errors. A one-shot HTTP call needs no unsubscribe, but a failed call still needs a visible message or a fallback.

The example below shows the fixed forms of items 2, 3, 4, and 5 in one component.

typescript
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, of, switchMap } from 'rxjs';

interface Student {
  id: number;
  name: string;
  marks: number;
}

interface Detail {
  id: number;
  address: string;
}

@Component({
  selector: 'app-student-table',
  template: `
    <p>Average: {{ average() }}</p>
    <button (click)="addStudent()">Add</button>
    @for (s of sorted(); track s.id) {
      <button (click)="selectedId.set(s.id)">{{ s.name }} ({{ s.marks }})</button>
    }
    <p>{{ detail()?.address ?? 'Select a student' }}</p>
  `,
})
export class StudentTableComponent {
  private readonly http = inject(HttpClient);

  readonly students = input.required<Student[]>();
  readonly extra = signal<Student[]>([]);
  readonly selectedId = signal<number | null>(null);

  // Item 2. Old form: {{ getAverage() }} called on every change detection pass.
  readonly all = computed(() => [...this.students(), ...this.extra()]);
  readonly average = computed(() => {
    const list = this.all();
    return list.length ? Math.round(list.reduce((sum, s) => sum + s.marks, 0) / list.length) : 0;
  });
  readonly sorted = computed(() => [...this.all()].sort((a, b) => b.marks - a.marks));

  // Items 3 and 5. Old form: subscribe inside subscribe with no cleanup.
  readonly detail = toSignal(
    toObservable(this.selectedId).pipe(
      switchMap((id) =>
        id === null
          ? of<Detail | null>(null)
          : this.http.get<Detail>(`/api/students/${id}`).pipe(catchError(() => of<Detail | null>(null))),
      ),
    ),
    { initialValue: null },
  );

  // Item 4. Old form: this.extra().push(...) which signals cannot detect.
  addStudent(): void {
    this.extra.update((list) => [...list, { id: 100 + list.length, name: 'New', marks: 50 }]);
  }
}

Angular 20.3, strict template check passes. The comments mark the old form of each pattern, which should not be written in new code.

Key points

  • NG0100 means state changed after it was rendered. Fix the data flow, not the symptom.
  • Replace template function calls with `computed` or a pure pipe.
  • Replace nested subscribes with flattening operators, and clean up with `toSignal` or `takeUntilDestroyed`.
  • Use immutable updates with OnPush and give `@for` a stable `track`.

Common mistakes

  • Fixing NG0100 with `setTimeout` and leaving the real design problem in place.
  • Turning off strict mode when the compiler complains instead of fixing the types.
  • Using `ChangeDetectorRef.detectChanges()` as a general repair tool.

Follow-ups

  • How would you reproduce NG0100 on purpose?
  • Why is a template function call different from a `computed`?
  • Which of these would you flag first in a code review, and why?

Tips

  • Prefer a real story from a review or debugging session in your own words, with the cause and the fix.
  • Always explain why a pitfall happens, not only the fix.
  • Say that you enable strict compiler options so many of these are caught early.

Evaluation rubric

  • Explains NG0100 and its real fixes.
  • Gives correct replacements for common anti-patterns.
  • Shows awareness of strict settings and review habits.
47.angular-0047Hardsenior

How would you migrate an older NgModule-based Angular application to the modern style (standalone, control flow, signals), and what is the order of work?

Update Angular one major version at a time with ng update, then run the official schematics in a safe order: standalone migration, control flow, inject(), route lazy loading, and then optional signal inputs, outputs and queries. Commit after each step, run tests, and migrate by feature so the app stays releasable. Old and new styles can live side by side.

Full answer

A migration is a project, not a command. A safe plan:

  1. Get the tests and the build green first. Without tests a migration is guesswork.
  2. Update the framework. ng update @angular/core @angular/cli moves one major version at a time. Read the update guide for each version, fix deprecations, and keep third-party libraries compatible.
  3. Standalone. ng generate @angular/core:standalone has three modes, run in order: convert declarations to standalone, remove unnecessary NgModules, and switch the bootstrap to bootstrapApplication. Commit after each mode. Libraries that still export NgModules can be imported into standalone components.
  4. Control flow. ng generate @angular/core:control-flow rewrites *ngIf, *ngFor, and *ngSwitch to @if, @for, and @switch. Review the generated track expressions. Then ng generate @angular/core:cleanup-unused-imports removes imports that are no longer needed.
  5. Dependency injection style. ng generate @angular/core:inject converts constructor parameters to inject().
  6. Routing. ng generate @angular/core:route-lazy-loading turns eager component routes into loadComponent. Convert class guards, resolvers, and interceptors to functions, and HttpClientModule to provideHttpClient().
  7. Signals (optional and gradual). signal-input-migration, output-migration, and signal-queries-migration convert @Input, @Output, and @ViewChild. Start with leaf components.
  8. Performance steps after that: OnPush, and then zoneless once the app is ready.

Keep a rule: new code uses the modern style, old code is converted when touched, or in planned batches. This avoids a big-bang rewrite. Review each migration diff, since schematics can produce code that compiles but needs manual tidying.

What does not need migration: NgModules still work and are still supported, and *ngIf still compiles in Angular 20 (it is deprecated). The team should decide by value: converting code that nobody changes has a low return.

typescript
// file: legacy/list.module.ts
import { CommonModule } from '@angular/common';
import { Component, Input, NgModule } from '@angular/core';

// LEGACY style: NgModule, decorator input, and structural directives.
@Component({
  selector: 'app-legacy-list',
  standalone: false,
  template: `
    <ul *ngIf="items.length > 0; else empty">
      <li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
    </ul>
    <ng-template #empty><p>No items</p></ng-template>
  `,
})
export class LegacyListComponent {
  @Input() items: { id: number; name: string }[] = [];

  trackById(_index: number, item: { id: number }): number {
    return item.id;
  }
}

@NgModule({
  declarations: [LegacyListComponent],
  imports: [CommonModule],
  exports: [LegacyListComponent],
})
export class LegacyListModule {}

// file: modern/list.component.ts
import { Component, input } from '@angular/core';

// MODERN style: standalone, signal input, and built-in control flow.
@Component({
  selector: 'app-list',
  template: `
    @if (items().length > 0) {
      <ul>
        @for (item of items(); track item.id) {
          <li>{{ item.name }}</li>
        }
      </ul>
    } @else {
      <p>No items</p>
    }
  `,
})
export class ListComponent {
  readonly items = input<{ id: number; name: string }[]>([]);
}

// file: modern/page.component.ts
import { Component } from '@angular/core';
import { LegacyListModule } from '../legacy/list.module';
import { ListComponent } from './list.component';

// Both styles can live in the same page during a gradual migration.
@Component({
  selector: 'app-page',
  imports: [LegacyListModule, ListComponent],
  template: `
    <app-legacy-list [items]="data" />
    <app-list [items]="data" />
  `,
})
export class PageComponent {
  data = [{ id: 1, name: 'Asha' }];
}

Angular 20.3, type-checked. The file shows one list component in the old style (legacy, kept compiling on purpose) and the same screen in the modern style.

Key points

  • Update with `ng update`, one major version at a time, with a green test suite.
  • Run schematics in order: standalone, control flow, inject, route lazy loading, signal APIs.
  • Commit per step and migrate by feature. Old and new can coexist.
  • Convert class-based guards, resolvers, and interceptors to functions.

Common mistakes

  • Updating several major versions at once and then being unable to find what broke.
  • Running every schematic in one commit, so the diff cannot be reviewed.
  • Rewriting stable, untouched modules for style only.

Follow-ups

  • How would you keep two teams productive while the migration runs?
  • Which migration gives the highest return first?
  • How do you handle a library that does not support standalone?

Tips

  • Give the order and the reason for it. It shows you have done or planned it.
  • Mention tests first, then small commits.
  • Say that you would not migrate everything at once and explain how you decide.

Evaluation rubric

  • Gives a safe, ordered plan with real schematic names.
  • Understands coexistence of styles.
  • Considers risk and cost.
48.angular-0048Hardsenior

What advanced HttpClient features should a senior developer know: HttpContext, withFetch, request cancellation, progress events, and the SSR transfer cache?

HttpContext carries typed per-request flags (skip auth, retry count) to interceptors without polluting headers. withFetch switches the backend to the Fetch API, which suits SSR. Unsubscribing cancels a request. With hydration, GET responses from the server are transferred to the browser through a transfer cache that can be tuned with withHttpTransferCacheOptions.

Full answer

HttpContext. Interceptors sometimes need to know something about one request: skip the auth header for a public endpoint, or retry this one three times. Headers are for the server, not for your own code. HttpContext is a typed bag for exactly this. Define new HttpContextToken<boolean>(() => false) (the function gives the default), call http.get(url, { context: new HttpContext().set(SKIP_AUTH, true) }), and read it in the interceptor with req.context.get(SKIP_AUTH). The context survives clone().

withFetch(). provideHttpClient(withFetch()) uses the fetch API instead of XMLHttpRequest. It works in Node for SSR without extra setup and is recommended for server rendering. Limits: fetch has no upload progress events, so a progress bar for uploads needs XHR (the default backend). Download progress works with reportProgress: true and observe: 'events'.

Cancellation. Unsubscribing from an HTTP Observable aborts the request. This is why switchMap cancels outdated calls, and why the async pipe cancels on destroy. For fetch-based code outside HttpClient use AbortController.

SSR transfer cache. When hydration is on, the server's GET and HEAD responses are serialised into the HTML. The browser's first identical request is answered from this cache and not sent again. By default requests with an Authorization header or a Proxy-Authorization header are not cached, and POST requests are skipped. Tune it with withHttpTransferCacheOptions({ includePostRequests, includeRequestsWithAuthHeaders, filter }) or turn it off with withNoHttpTransferCache(). Make sure that personalised responses are not cached into HTML that a CDN may store for everybody.

Other points: HttpParams and HttpHeaders are immutable, responseType changes the result type ('text', 'blob'), and observe: 'response' gives headers and status.

typescript
// file: tokens.ts
import { HttpContextToken } from '@angular/common/http';

export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
export const RETRIES = new HttpContextToken<number>(() => 0);

// file: interceptors.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { retry } from 'rxjs';
import { RETRIES, SKIP_AUTH } from './tokens';

export const authInterceptor: HttpInterceptorFn = (req, next) =>
  req.context.get(SKIP_AUTH)
    ? next(req)
    : next(req.clone({ setHeaders: { Authorization: 'Bearer demo-token' } }));

export const retryInterceptor: HttpInterceptorFn = (req, next) =>
  next(req).pipe(retry(req.context.get(RETRIES)));

// file: news.service.ts
import { HttpClient, HttpContext } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { RETRIES, SKIP_AUTH } from './tokens';

@Injectable({ providedIn: 'root' })
export class NewsService {
  private readonly http = inject(HttpClient);

  publicHeadlines(): Observable<string[]> {
    const context = new HttpContext().set(SKIP_AUTH, true).set(RETRIES, 2);
    return this.http.get<string[]>('/api/public/headlines', { context });
  }
}

// file: app.config.ts
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
import { authInterceptor, retryInterceptor } from './interceptors';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withFetch(), withInterceptors([authInterceptor, retryInterceptor])),
    provideClientHydration(
      withHttpTransferCacheOptions({
        includePostRequests: false,
        includeRequestsWithAuthHeaders: false,
        filter: (req) => !req.url.includes('/api/private'),
      }),
    ),
  ],
};

Angular 20.3, type-checked. The retry count is read from the context in the same interceptor.

Key points

  • `HttpContextToken` plus `HttpContext` pass typed per-request options to interceptors.
  • `withFetch()` is recommended for SSR but has no upload progress.
  • Unsubscribing cancels the request.
  • The SSR transfer cache serves the browser's first GET from server data. Tune it with `withHttpTransferCacheOptions`.

Common mistakes

  • Using a custom header such as `X-Skip-Auth` to signal the interceptor, which also sends it to the server.
  • Mutating `HttpParams` and expecting the change in place. It returns a new object.
  • Letting personalised data go through the transfer cache into cacheable HTML.

Follow-ups

  • How would you add a progress bar for file uploads?
  • What happens to an in-flight request when the user navigates away?
  • Why are requests with an Authorization header excluded from the transfer cache by default?

Tips

  • Use the skip-auth example for HttpContext. It is concrete and short.
  • Know the `fetch` limitation (upload progress).
  • Mention the security side of the transfer cache. Senior reviewers care about data leaks.

Evaluation rubric

  • Uses HttpContext correctly in an interceptor.
  • Understands the fetch backend and its limits.
  • Understands the transfer cache and its risks.
49.angular-0049Hardsenior

What is the resource() API, how does it relate to signals and RxJS, and what is its status in Angular 20?

resource() loads asynchronous data into signals. It re-runs its loader whenever the signals read in its params function change, cancels the previous load with an AbortSignal, and exposes value, status, error, isLoading and reload as signals. rxResource does the same with Observables. In Angular 19 and 20 these APIs are experimental, so the API may still change.

Full answer

Before resource, loading data on a signal change meant toObservable, switchMap, and toSignal, plus manual loading and error flags. A resource packages that pattern.

ts
course = resource({
  params: () => ({ id: this.id() }),
  loader: async ({ params, abortSignal }) => { ... fetch(..., { signal: abortSignal }) ... },
});

How it works:

  • params is a reactive function. When the signals it reads change, the loader runs again. If params returns undefined, the resource goes to idle and does not load, which handles "no id yet".
  • loader returns a Promise. It receives the current params and an abortSignal. When params change before the previous load finishes, the old load is aborted and its result is ignored.
  • State signals: value(), status() (idle, loading, reloading, resolved, error, local), error(), and isLoading(). hasValue() is a safe check. reload() runs the loader again. set() and update() write a local value, for example for optimistic updates.
  • rxResource (in @angular/core/rxjs-interop) uses a stream function that returns an Observable, so HttpClient, interceptors, and testing tools work unchanged.

Status warning: resource, rxResource, and httpResource are marked experimental in Angular 19 and 20 (the parameter name changed from request to params in 20). Do not build a core library on them without a plan for changes.

When to use: simple "fetch when this signal changes" cases. When not: complex flows with debounce, retries, merging several streams, or write operations (use RxJS), and mutations (resource is for reading).

Remember to handle the error state in the template. Reading value() while in error throws, so check hasValue() or status() first.

typescript
import { HttpClient } from '@angular/common/http';
import { Component, inject, input, resource } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';

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

@Component({
  selector: 'app-course-view',
  template: `
    @if (course.isLoading()) {
      <p>Loading...</p>
    } @else if (course.error(); as err) {
      <p role="alert">Could not load: {{ err.message }}</p>
      <button (click)="course.reload()">Try again</button>
    } @else if (course.hasValue()) {
      <h1>{{ course.value().title }}</h1>
    } @else {
      <p>Choose a course.</p>
    }
  `,
})
export class CourseViewComponent {
  private readonly http = inject(HttpClient);
  readonly id = input<string>();

  // Promise based: fetch plus AbortSignal.
  readonly course = resource({
    params: () => this.id(), // undefined means idle
    loader: async ({ params, abortSignal }): Promise<Course> => {
      const response = await fetch(`/api/courses/${params}`, { signal: abortSignal });
      if (!response.ok) {
        throw new Error(`Server answered ${response.status}`);
      }
      return (await response.json()) as Course;
    },
  });

  // Observable based: same idea with HttpClient and its interceptors.
  readonly related = rxResource({
    params: () => this.id(),
    stream: ({ params }) => this.http.get<Course[]>(`/api/courses/${params}/related`),
    defaultValue: [] as Course[],
  });
}

Angular 20.3 (experimental API, may change). Needs `provideHttpClient()` for the `rxResource` example and an API that returns JSON for both.

Key points

  • `params` is reactive; the loader reruns when it changes. `undefined` params means idle.
  • Old loads are aborted through `abortSignal`.
  • `value`, `status`, `error`, `isLoading`, `reload`, `set` are all part of the resource.
  • Experimental in Angular 19 and 20. Use RxJS for complex flows.

Common mistakes

  • Reading `value()` in the error state without a check, which throws.
  • Ignoring `abortSignal`, so cancelled requests still finish and use bandwidth.
  • Using resource for writes such as POST requests.

Follow-ups

  • How does `rxResource` differ from `resource`?
  • What is the difference between `loading` and `reloading`?
  • When would you still choose `toObservable` and `switchMap`?

Tips

  • State the experimental status first. Interviewers value honesty about maturity.
  • Compare it with the signal plus `switchMap` pattern to show you understand what it replaces.
  • Mention `abortSignal` and the idle state with undefined params.

Evaluation rubric

  • Explains reactive params, loader, and abort.
  • Lists the resource state signals.
  • States the experimental status and limits.
50.angular-0050Hardsenior

What does the Angular compiler do during ng build, what are AOT and Ivy, and how do strict template checks and tree-shaking fit in?

The Angular compiler (ngtsc) turns decorators and templates into plain JavaScript instructions ahead of time (AOT), checks template types, and leaves a static definition on each class. Ivy is the rendering engine that runs these instructions. Because everything is static, bundlers can drop unused code. JIT compiles in the browser and is used mainly in tests and special cases.

Full answer

Browsers cannot read Angular templates. Somebody has to turn {{ marks() }} and (click)="add()" into JavaScript. There are two moments to do it.

AOT (ahead of time) is the default. During ng build and ng serve the compiler runs as part of TypeScript compilation. It reads each decorator, parses the template, and writes instructions into the class as static fields: ɵfac (how to create the class) and ɵcmp (the component definition with a template function). The output at the end of this answer is real compiler output for a tiny component.

Why AOT: the browser does not need to download or run the compiler (smaller and faster start-up), template errors become build errors, and templates are never parsed from strings at runtime, which also helps security.

Ivy is the name of the renderer and compiler design since Angular 9. A template function has two parts: a creation block (run once, creates DOM nodes) and an update block (run at each change detection, updates bindings). Because every component carries its own definition and refers to only the instructions it uses, bundlers can tree-shake unused framework features. Locality is also why each component compiles independently, which speeds up incremental builds.

Template type-checking. With strictTemplates: true (set by default in new projects) the compiler checks bindings against component types: a wrong input type, a missing property, or a missing import fails the build. It also reports things such as an arrow function inside a template, which the template syntax does not allow.

JIT (just in time) compiles in the browser at runtime. It is used in some test setups and in rare dynamic cases, not in production builds.

Build pipeline in current CLI: the application builder uses esbuild for bundling and Vite for the dev server, supports SSR and prerendering, produces hashed file names for caching, and enforces budgets from angular.json. Libraries are compiled in a partial format that the application's build links against its own Angular version.

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

@Component({
  selector: 'app-mark',
  template: `
    <p>Marks: {{ marks() }}</p>
    <button (click)="add()">Add</button>
  `,
})
export class MarkComponent {
  readonly marks = signal(0);

  add(): void {
    this.marks.update((m) => m + 1);
  }
}

/*
Compiler output (trimmed): the template becomes a function with a creation block
(rf & 1) and an update block (rf & 2).

static ɵcmp = i0.ɵɵdefineComponent({
  type: MarkComponent,
  selectors: [["app-mark"]],
  decls: 4, vars: 1, consts: [[3, "click"]],
  template: function MarkComponent_Template(rf, ctx) {
    if (rf & 1) {                       // creation: runs once
      i0.ɵɵdomElementStart(0, "p");
      i0.ɵɵtext(1);
      i0.ɵɵdomElementEnd();
      i0.ɵɵdomElementStart(2, "button", 0);
      i0.ɵɵdomListener("click", function MarkComponent_Template_button_click_2_listener() { return ctx.add(); });
      i0.ɵɵtext(3, "Add");
      i0.ɵɵdomElementEnd();
    }
    if (rf & 2) {                       // update: runs on each check
      i0.ɵɵadvance();
      i0.ɵɵtextInterpolate1("Marks: ", ctx.marks());
    }
  }
});
*/

Angular 20.3 and TypeScript 5.8. The comment block at the end is the real output of `ngc` (Angular compiler CLI) for this component with `strictTemplates` enabled. Names and numbers in it can differ between Angular versions. Run `npx ngc -p tsconfig.json` with `outDir` set to see your own.

Key points

  • AOT compiles templates at build time into `ɵfac` and `ɵcmp` static definitions.
  • Ivy runs template functions with creation and update blocks and allows tree-shaking.
  • `strictTemplates` turns template mistakes into build errors.
  • JIT compiles in the browser and is not used for production builds.

Common mistakes

  • Believing templates are interpreted as HTML strings at runtime.
  • Turning off `strictTemplates` to silence errors instead of fixing the types.
  • Thinking Ivy is a library you install. It is built into the compiler and runtime.

Follow-ups

  • What is the difference between the creation and the update block of a template function?
  • How are Angular libraries compiled so that they work with different app versions?
  • How would you investigate a bundle that is too large?

Tips

  • Show the creation versus update block. It proves you looked at the output.
  • Link the answer to practical effects: errors at build time, smaller bundles, faster start-up.
  • Avoid claiming specific percentages for speed or size. Say what you measured.

Evaluation rubric

  • Explains AOT versus JIT and what the compiler emits.
  • Understands Ivy's template function model and tree-shaking.
  • Knows strict template checking and the modern builder.
51.angular-0051Easyfresher

What are the ways components can share data in Angular, and when do you use input/output, a shared service, or a view query?

Parent to child uses inputs, child to parent uses outputs, and unrelated or distant components share state through a service that holds signals. A parent can also call a child method through a view query, but that is the last choice. Pick the narrowest tool that works.

Full answer

Angular gives several ways to move data. The best choice depends on how the two components are related.

  1. Parent to child: inputs. The parent binds a value with [title]="x" and the child reads title(). Data flows down only.
  2. Child to parent: outputs. The child emits an event with output(), and the parent listens with (chosen)="handler($event)". The child does not know who is listening, so it stays reusable.
  3. Siblings or distant components: a shared service. A service provided in root (or at a route) holds a signal, and any component that injects it can read or update it. This avoids passing data through many layers (prop drilling).
  4. Parent calls child: a view query, viewChild(ChildComponent), then call a public method. Use it for imperative actions such as focus() or reset(), not for ordinary data.
  5. Content projection: the parent passes markup in with <ng-content>, for cases where the parent decides what the child shows.
  6. Router: route parameters, query parameters, and resolver data carry data between pages.

A school example: a class teacher (parent) gives each student card (child) a name through an input. When a student presses "Absent", the card emits an event, and the teacher updates the register. A notice board (service) lets the library and the canteen see the same announcement without talking to each other.

Rules of thumb: prefer inputs and outputs for direct relations, because the data flow is easy to follow. Use a service when more than two levels are involved or when state outlives a component. Avoid reaching into another component's internals.

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

@Injectable({ providedIn: 'root' })
export class NoticeBoard {
  readonly message = signal('No notice today');
}

@Component({
  selector: 'app-student-card',
  template: `
    <p>{{ name() }}</p>
    <button (click)="absent.emit(name())">Absent</button>
  `,
})
export class StudentCardComponent {
  name = input.required<string>();
  absent = output<string>();
}

@Component({
  selector: 'app-notice-reader',
  template: `<p>Notice: {{ board.message() }}</p>`,
})
export class NoticeReaderComponent {
  constructor(protected readonly board: NoticeBoard) {}
}

@Component({
  selector: 'app-register',
  imports: [StudentCardComponent, NoticeReaderComponent],
  template: `
    @for (n of names; track n) {
      <app-student-card [name]="n" (absent)="markAbsent($event)" />
    }
    <p>Absent: {{ absentNames().join(', ') || 'none' }}</p>
    <app-notice-reader />
  `,
})
export class RegisterComponent {
  names = ['Asha', 'Imran', 'Meera'];
  absentNames = signal<string[]>([]);

  constructor(private readonly board: NoticeBoard) {}

  markAbsent(name: string): void {
    this.absentNames.update((list) => (list.includes(name) ? list : [...list, name]));
    this.board.message.set(`${name} is absent today`);
  }
}

Angular 20.3, strict template check passes. Click "Absent" on any card and the summary and the notice both update.

Key points

  • Down: `input()`. Up: `output()`. Across: a service with signals.
  • `viewChild` is for imperative calls such as `focus()`, not for sharing state.
  • Prefer the narrowest tool: direct relation means input and output.
  • A service holding a signal avoids passing data through many levels.

Common mistakes

  • Passing a value through five components with inputs instead of using a service.
  • Mutating an object received through an input. The parent's copy changes too.
  • Making a child depend on a specific parent by injecting it. The child is no longer reusable.

Follow-ups

  • How would two components in different routes share an unsaved form?
  • Why should a child not change an input object directly?
  • When would you choose an event bus (Subject) over a signal in a service?

Tips

  • Describe the relationship first (parent, sibling, distant), then name the tool.
  • Say that outputs make a child reusable because it does not know its listener.
  • Mention that a root service is shared for the whole app, so scope it to a route when it should reset.

Evaluation rubric

  • Names inputs, outputs, services, and queries with correct direction of data.
  • Gives a rule for choosing.
  • Avoids anti-patterns such as mutation and tight coupling.
52.angular-0052Easyfresher

How does Angular scope component styles, what are the ViewEncapsulation modes, and how do you style a child component from outside?

By default Angular rewrites component CSS so it only affects that component's own template (Emulated encapsulation). ViewEncapsulation.None makes the styles global and ShadowDom uses the browser's real shadow DOM. Use :host to style the component's own element and CSS custom properties to let a parent theme a child. ::ng-deep is deprecated.

Full answer

CSS is global in a web page, so a rule such as h2 { color: red } normally changes every h2. Angular avoids this with view encapsulation, which is set in the encapsulation option of @Component.

  • Emulated (default). Angular adds a generated attribute (like _ngcontent-abc-c12) to every element of the component and rewrites each selector to include it. Styles stay inside the component, and global styles still reach in. It is not a real shadow DOM.
  • None. Styles are added to the page unchanged, so they are global. Useful for a theme file or when you must style third-party markup.
  • ShadowDom. The component uses the browser's native shadow DOM. Strong isolation, and global styles do not enter. Fonts and global resets need extra care.

Selectors inside a component:

  • :host selects the component's own element, for example :host { display: block; }. Custom elements are display: inline by default, so setting display: block here is a common first step.
  • :host(.active) selects the host when it has a class.
  • :host-context(.dark) selects the host when an ancestor has the class (used for themes).

Styling a child from outside. The parent's scoped CSS cannot reach into a child's template. Good options, from best to worst:

  1. Expose CSS custom properties in the child (color: var(--badge-color, navy)) and set them from the parent.
  2. Give the child an input such as variant.
  3. Put the rule in a global stylesheet.
  4. ::ng-deep pierces encapsulation, but it is deprecated and should only appear in old code.

Remember that styles in styles or styleUrl are loaded with the component and removed from the page when the last instance is destroyed.

typescript
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-badge',
  template: `<span class="label"><ng-content /></span>`,
  styles: `
    :host {
      display: inline-block;
      margin: 4px;
    }
    :host(.large) .label {
      font-size: 1.5rem;
    }
    .label {
      color: white;
      padding: 2px 8px;
      border-radius: 8px;
      background: var(--badge-color, navy);
    }
  `,
})
export class BadgeComponent {}

@Component({
  selector: 'app-theme-demo',
  imports: [BadgeComponent],
  encapsulation: ViewEncapsulation.Emulated,
  template: `
    <h2>Result</h2>
    <app-badge>Passed</app-badge>
    <app-badge class="large" style="--badge-color: darkred">Failed</app-badge>
  `,
  styles: `
    /* Applies to this component's h2 only, not to the h2 elements of other components. */
    h2 {
      color: teal;
    }
  `,
})
export class ThemeDemoComponent {}

@Component({
  selector: 'app-global-skin',
  encapsulation: ViewEncapsulation.None,
  template: `<p class="notice">This rule is global</p>`,
  styles: `
    .notice {
      font-style: italic;
    }
  `,
})
export class GlobalSkinComponent {}

Angular 20.3, strict template check passes. Set `--badge-color` on the parent or on any ancestor to change the badge colour.

Key points

  • Emulated is the default and scopes styles by adding attributes. `None` is global. `ShadowDom` is native isolation.
  • `:host` styles the component's own element. Set `display` there.
  • CSS custom properties are the clean way for a parent to theme a child.
  • `::ng-deep` is deprecated. Avoid it in new code.

Common mistakes

  • Forgetting that a component's host element is `display: inline` and then wondering why width and margin do not work.
  • Using `ViewEncapsulation.None` in many components, which brings back global CSS conflicts.
  • Using `::ng-deep` to override a library instead of its supported theming variables.

Follow-ups

  • How can you apply a global style to one specific component only?
  • What changes in styling when you use `ShadowDom`?
  • How does Angular Material expose theming without `::ng-deep`?

Tips

  • Say that encapsulation is emulated by attributes. It shows you understand the mechanism.
  • Offer CSS variables as the answer for child styling.
  • Mention that `::ng-deep` is deprecated, and that you would only keep it in old code.

Evaluation rubric

  • Names the three modes correctly.
  • Uses :host and CSS custom properties.
  • Knows ng-deep is deprecated.
53.angular-0053Easyfresher

When is it acceptable to touch the DOM directly in Angular, and what are ElementRef and Renderer2 for?

Prefer template bindings. When you must change the DOM, inject ElementRef to reach the host element and Renderer2 to change it in a platform-safe way. Direct document or window access breaks server rendering, and innerHTML bypasses Angular's protections. Browser-only code belongs in afterNextRender.

Full answer

Angular updates the DOM for you through bindings: [class.active], [style.width.px], [attr.aria-label], @if, and @for. Most of the time this is enough, and it works in every environment.

Sometimes you need more: focusing an input, measuring an element, or wrapping a third-party widget. Then use these tools:

  • ElementRef. inject(ElementRef) gives the host element of a component or directive, through nativeElement. It is a plain object that holds the DOM node.
  • Renderer2. An abstraction for changing the DOM: addClass, setStyle, setAttribute, listen, createElement. On the server it works on Angular's server DOM, and with a custom renderer (for example in tests) it still works. Using nativeElement.style.x also works in the browser, but fails on platforms without a real DOM.
  • viewChild() gives a specific element of your template without a global query.
  • afterNextRender runs browser-only code after the first render, so window, document, localStorage, and layout measurements are safe there.

Things to avoid:

  • document.querySelector inside components. It can find elements from other components and does not work on the server.
  • nativeElement.innerHTML = userText. This skips Angular's sanitization and can allow cross-site scripting. Use [innerHTML] instead, which sanitizes.
  • Reading layout (offsetHeight) in loops while writing styles, which forces repeated layout work.

Angular's own documentation tells you to use ElementRef with care, because direct access makes code harder to test and to run on the server.

typescript
import { Directive, ElementRef, OnDestroy, OnInit, Renderer2, afterNextRender, inject } from '@angular/core';

@Directive({ selector: '[appFocusRing]' })
export class FocusRingDirective implements OnInit, OnDestroy {
  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
  private readonly renderer = inject(Renderer2);
  private stopFocus?: () => void;
  private stopBlur?: () => void;

  constructor() {
    afterNextRender(() => {
      // Browser only: safe to read layout here.
      console.log('Width:', this.host.nativeElement.offsetWidth);
    });
  }

  ngOnInit(): void {
    const el = this.host.nativeElement;
    this.renderer.setAttribute(el, 'tabindex', '0');
    this.stopFocus = this.renderer.listen(el, 'focus', () => this.renderer.addClass(el, 'ring'));
    this.stopBlur = this.renderer.listen(el, 'blur', () => this.renderer.removeClass(el, 'ring'));
  }

  ngOnDestroy(): void {
    this.stopFocus?.();
    this.stopBlur?.();
  }
}

Angular 20.3. Use as `<p appFocusRing>Click or tab to focus</p>`. The directive adds a class when the element is clicked and removes it on blur.

Key points

  • Use bindings first. Reach for `ElementRef` or `Renderer2` only when bindings cannot do the job.
  • `Renderer2` changes the DOM in a platform-safe way. `ElementRef` gives the host node.
  • Browser-only work goes in `afterNextRender`. Avoid `document.querySelector`.
  • Never assign user text to `innerHTML` through `nativeElement`.

Common mistakes

  • Using `document.getElementById` in a component, which breaks SSR and finds elements from other components.
  • Setting `innerHTML` through `nativeElement` and bypassing sanitization.
  • Querying the DOM in the constructor, before the view exists.

Follow-ups

  • Why does `Renderer2` exist if `nativeElement` works in the browser?
  • How would you measure an element's width safely with SSR enabled?
  • What does `[innerHTML]` do to the HTML you bind?

Tips

  • Start with "bindings first". Interviewers want to hear you avoid DOM access by default.
  • Name the SSR reason, since that is the practical cost.
  • Say what you would use instead for each case: `viewChild`, `afterNextRender`, `[innerHTML]`.

Evaluation rubric

  • Knows the roles of ElementRef and Renderer2.
  • Names SSR and security risks of direct DOM access.
  • Prefers bindings and lifecycle-safe hooks.
54.angular-0054Easyfresher

What is the difference between route parameters, query parameters and fragments, and how do you read and change them?

Route parameters are part of the path (/courses/42) and identify a resource. Query parameters come after a question mark (?page=2&sort=name) and describe optional state such as filters. A fragment follows a hash. Read them with input binding or ActivatedRoute, and change them with routerLink or Router.navigate.

Full answer

Take the URL /courses/42?page=2&sort=name#reviews.

  • Route parameter id = 42. It is declared in the route path (courses/:id). It is required, because without it the route does not match. Use it for identity.
  • Query parameters page = 2 and sort = name. They are optional and are not part of route matching. Use them for filters, sorting, and paging, so a user can share or bookmark the filtered view.
  • Fragment reviews. Used for in-page anchors.

Reading them:

  • With withComponentInputBinding() in provideRouter, route parameters and query parameters are set on component inputs with the same name: id = input.required<string>() and page = input<string>().
  • With ActivatedRoute: route.paramMap and route.queryParamMap are Observables. route.snapshot.paramMap is a one-time read. Use the Observable when the same component instance is reused for different ids, for example when going from /courses/1 to /courses/2, because the snapshot does not change.
  • toSignal(route.queryParamMap) converts it to a signal.

Changing them:

  • Template: <a [routerLink]="['/courses', id]" [queryParams]="{ page: 3 }" queryParamsHandling="merge">.
  • Code: router.navigate([], { relativeTo: route, queryParams: { page: 3 }, queryParamsHandling: 'merge' }). With an empty command array it stays on the same route and only changes the query. merge keeps the other query parameters, and preserve keeps all of them.

Remember that all parameter values are strings. Convert numbers yourself, and validate them, since users can edit the URL.

typescript
import { Component, computed, inject, input } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { map } from 'rxjs';

@Component({
  selector: 'app-course-page',
  imports: [RouterLink],
  template: `
    <h1>Course {{ id() }}</h1>
    <p>Page {{ page() }}, sorted by {{ sort() }}</p>
    <button (click)="goToPage(page() + 1)">Next page</button>
    <a [routerLink]="[]" [queryParams]="{ sort: 'name' }" queryParamsHandling="merge">Sort by name</a>
  `,
})
export class CoursePageComponent {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);

  // Route parameter (courses/:id), bound by withComponentInputBinding().
  readonly id = input.required<string>();

  // Query parameters read through ActivatedRoute. Values are strings.
  private readonly query = toSignal(this.route.queryParamMap.pipe(map((q) => ({ page: q.get('page'), sort: q.get('sort') }))), {
    initialValue: { page: null, sort: null },
  });

  readonly page = computed(() => {
    const n = Number(this.query().page);
    return Number.isInteger(n) && n > 0 ? n : 1;
  });
  readonly sort = computed(() => this.query().sort ?? 'date');

  goToPage(page: number): void {
    void this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { page },
      queryParamsHandling: 'merge',
    });
  }
}

Angular 20.3, strict template check passes. The component works at a path like `courses/:id` when the router uses `withComponentInputBinding()`.

Key points

  • Route params identify the resource. Query params hold optional state. The fragment is an anchor.
  • Read with input binding (`withComponentInputBinding`) or with `ActivatedRoute` observables.
  • Use `queryParamsHandling: 'merge'` to change one query parameter and keep the others.
  • Values are strings and can be edited by the user, so validate them.

Common mistakes

  • Using `route.snapshot` in a component that is reused for different ids, so the page does not update.
  • Navigating with `queryParams` without `merge`, which drops the other filters.
  • Treating `page` as a number without converting it.

Follow-ups

  • Why does Angular reuse the component when only the id changes?
  • When would you store state in the query string instead of a service?
  • How do you read matrix parameters?

Tips

  • Use the filter and paging example for query parameters. It shows a clear reason: shareable URLs.
  • Mention reuse of component instances. It is the classic bug.
  • Say that you validate and convert values.

Evaluation rubric

  • Distinguishes the three parts of a URL.
  • Reads and updates parameters with current APIs.
  • Understands snapshot versus observable.
55.angular-0055Easyfresher

Which Angular CLI commands do you use every day, and what files does ng generate component create?

The CLI creates projects (ng new), generates code (ng generate), runs a dev server (ng serve), builds for production (ng build), runs tests (ng test), and upgrades versions (ng update). ng generate component makes a class, a template, a style file, and a spec, using the project's defaults from angular.json.

Full answer

The Angular CLI is the ng command. The commands you will use most:

  • ng new shop creates a project with the recommended setup.
  • ng serve starts a development server with live reload.
  • ng generate component student-card (short form ng g c student-card) creates files. Other generators: service, directive, pipe, guard, interceptor, resolver, class, interface, enum.
  • ng build builds the app. The default configuration is production, which minifies, tree-shakes, and adds hashes to file names. Use ng build --configuration development for an unoptimised build with source maps.
  • ng test runs unit tests, and ng e2e runs end-to-end tests if a tool is configured.
  • ng update upgrades Angular packages with migration scripts. ng add installs a package and runs its setup, for example ng add @angular/material.
  • ng version and ng config show or change settings.

What ng generate component student-card creates in Angular 20: student-card.ts (the class), student-card.html, student-card.css, and student-card.spec.ts. The component is standalone, and the class is named StudentCard without the old Component suffix. Older projects (and the older CLI) create student-card.component.ts and a class named StudentCardComponent. Both are valid. Flags such as --inline-template, --inline-style, --skip-tests, and --change-detection OnPush change the output. Defaults can be set in angular.json under schematics.

Key files in a project: angular.json (build, serve, and test settings), tsconfig.json (TypeScript options), package.json, src/main.ts (bootstrap), src/app/app.config.ts (providers), src/app/app.routes.ts (routes), and src/index.html.

The CLI is also what makes upgrades predictable. ng update moves code with schematics, so read its messages and commit before running it.

typescript
// Commands:
//   ng new shop
//   ng generate component student-card
//   ng serve
//   ng test
//   ng build

// file: student-card.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-student-card',
  imports: [],
  templateUrl: './student-card.html',
  styleUrl: './student-card.css',
})
export class StudentCard {}

// file: student-card.html
<p>student-card works!</p>

// file: student-card.css
/* empty file */

// file: student-card.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { StudentCard } from './student-card';

describe('StudentCard', () => {
  let component: StudentCard;
  let fixture: ComponentFixture<StudentCard>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [StudentCard],
    }).compileComponents();

    fixture = TestBed.createComponent(StudentCard);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

The files below are the real output of `ng generate component student-card` in a fresh Angular 20.3 project (the `.css` file is empty). The spec was run with `ng test` in headless Chrome and passes. The commands are listed in the first comment.

Key points

  • `ng new`, `serve`, `generate`, `build`, `test`, `update`, `add` cover daily work.
  • `ng generate component` creates a class, template, style, and spec file.
  • Angular 20 names the class without the `Component` suffix. Older code uses it. Both work.
  • `angular.json` holds the build and generator settings.

Common mistakes

  • Hand-writing boilerplate that the generators create with correct defaults.
  • Running `ng update` with uncommitted changes, which makes the migration diff hard to read.
  • Confusing `ng add` (installs and configures) with `npm install` (only installs).

Follow-ups

  • What is the difference between `ng build` configurations?
  • How do you change the defaults of `ng generate` for the whole project?
  • What does `ng update` actually do?

Tips

  • Mention that generated names changed in Angular 20, so you can read both styles.
  • Say how you would use `ng update` safely: clean working tree, small steps.
  • Know where the settings live (`angular.json`).

Evaluation rubric

  • Lists the main commands with their purpose.
  • Knows what the component generator creates.
  • Understands the project's key files.
56.angular-0056Easyfresher

What are Subject, BehaviorSubject, ReplaySubject and AsyncSubject, and how do they differ?

A Subject is both an Observable and an observer, so you can push values into it and many subscribers receive them (multicast). BehaviorSubject needs an initial value and gives new subscribers the latest value. ReplaySubject replays a set number of past values. AsyncSubject emits only the last value, and only when it completes.

Full answer

A normal Observable such as http.get() is cold. Each subscriber starts its own run. A Subject is hot: it exists on its own, you call next() on it, and every current subscriber receives the value.

The four kinds differ in what a late subscriber receives:

  • Subject: nothing from the past. A subscriber sees only values emitted after it subscribed. Good for events such as "user clicked save".
  • BehaviorSubject(initial): always holds a current value. A new subscriber immediately gets the latest one. You can read it with .value or getValue(). Good for state such as "current user".
  • ReplaySubject(n): remembers the last n values and replays them to each new subscriber. Good for a short history.
  • AsyncSubject: emits only the last value, and only when complete() is called. Good for a single result that is shared.

Errors and completion: after error() or complete() a Subject is finished. A late subscriber to a completed Subject receives only the completion (and replayed values for a ReplaySubject).

Practical rules: expose a Subject as an Observable with asObservable() so that outside code cannot call next(). In modern Angular many uses of BehaviorSubject for state are better served by a signal, which has a synchronous read and no subscription to clean up. Subjects are still the right tool for event streams such as search input or a message bus.

The script below shows what each late subscriber receives.

typescript
import { AsyncSubject, BehaviorSubject, ReplaySubject, Subject } from 'rxjs';

const subject = new Subject<number>();
const behavior = new BehaviorSubject<number>(0);
const replay = new ReplaySubject<number>(2);
const last = new AsyncSubject<number>();

for (const n of [1, 2, 3]) {
  subject.next(n);
  behavior.next(n);
  replay.next(n);
  last.next(n);
}

// Everyone subscribes late, after 1, 2, 3 were emitted.
subject.subscribe((v) => console.log('Subject       ', v)); // nothing yet
behavior.subscribe((v) => console.log('BehaviorSubject', v)); // 3
replay.subscribe((v) => console.log('ReplaySubject  ', v)); // 2, 3
last.subscribe((v) => console.log('AsyncSubject   ', v)); // waits for complete

console.log('--- emit 4 and complete');
subject.next(4);
behavior.next(4);
replay.next(4);
last.next(4);
last.complete();

// Expose state without letting outsiders push values.
class Counter {
  private readonly state = new BehaviorSubject(0);
  readonly value$ = this.state.asObservable();

  increment(): void {
    this.state.next(this.state.value + 1);
  }
}

const counter = new Counter();
counter.value$.subscribe((v) => console.log('Counter', v));
counter.increment();

Tested with RxJS 7 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), twice with identical output.

Key points

  • A Subject is hot and multicast. `next()` pushes a value to all subscribers.
  • `BehaviorSubject` has a current value. `ReplaySubject(n)` replays `n` values. `AsyncSubject` gives the last value on completion.
  • Expose it with `asObservable()` and keep `next()` private.
  • For state, a signal is often simpler. For events, use a Subject.

Common mistakes

  • Exposing a public `BehaviorSubject` so any component can call `next()` on it.
  • Using a plain `Subject` for state, so late subscribers see nothing.
  • Forgetting to unsubscribe from a Subject that never completes.

Follow-ups

  • What is the difference between a cold and a hot Observable?
  • Why would you pick a signal instead of a BehaviorSubject?
  • What happens if you subscribe to a completed ReplaySubject?

Tips

  • Make a table in your head: what does a late subscriber get? It is the clearest answer.
  • Mention `asObservable()` to show you think about encapsulation.
  • Say that you use signals for state in new code.

Evaluation rubric

  • Explains hot versus cold and multicast.
  • Distinguishes all four subject types by late-subscriber behaviour.
  • Knows the encapsulation practice.
57.angular-0057Easyfresher

How do template-driven forms work with ngModel, and how do you show validation errors?

In a template-driven form each input uses ngModel with a name attribute, and Angular creates the form model behind the scenes. A template reference such as #email="ngModel" exposes the control state (valid, touched, errors), and HTML validators such as required and minlength become Angular validators.

Full answer

Template-driven forms keep the setup in the template. You need FormsModule in imports.

How it works:

  1. <form #f="ngForm" (ngSubmit)="save(f)">. The NgForm directive attaches automatically to a form tag and collects all controls inside it.
  2. <input name="email" [(ngModel)]="user.email" required email #email="ngModel">. ngModel registers the input as a control, and the name attribute is required inside a form, since it becomes the control's key.
  3. HTML attributes required, minlength, maxlength, pattern, and email activate matching Angular validators.
  4. #email="ngModel" exports the control into a template variable, so you can read email.invalid, email.touched, and email.errors.

Showing errors only after the user touched the field avoids red text at the start: @if (email.invalid && email.touched) { ... }. After a failed submit you can show all errors by checking f.submitted.

[(ngModel)] is two-way binding, that is [ngModel] plus (ngModelChange). Updates happen asynchronously, so values are not available in the same tick as the first render.

When to choose it: simple forms (login, a search box, a feedback form). The limits: validation rules live in HTML and are harder to unit test, dynamic fields are awkward, and cross-field rules need a directive. For anything larger, use reactive forms.

Typed values: ngModel is not typed, so user should be a typed object in the class.

typescript
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';

interface Feedback {
  email: string;
  message: string;
}

@Component({
  selector: 'app-feedback-form',
  imports: [FormsModule],
  template: `
    <form #f="ngForm" (ngSubmit)="send(f)">
      <label for="email">Email</label>
      <input id="email" name="email" type="email" required email [(ngModel)]="model.email" #email="ngModel" />
      @if (email.invalid && (email.touched || f.submitted)) {
        <small role="alert">
          @if (email.errors?.['required']) { Email is required. }
          @else { Enter a valid email address. }
        </small>
      }

      <label for="message">Message</label>
      <textarea id="message" name="message" required minlength="10" [(ngModel)]="model.message" #message="ngModel"></textarea>
      @if (message.invalid && (message.touched || f.submitted)) {
        <small role="alert">Write at least 10 characters.</small>
      }

      <button type="submit" [disabled]="f.invalid">Send</button>
    </form>
  `,
})
export class FeedbackFormComponent {
  model: Feedback = { email: '', message: '' };

  send(form: NgForm): void {
    if (form.invalid) {
      return;
    }
    console.log('Sending', this.model);
    form.resetForm();
  }
}

Angular 20.3, strict template check passes. The submit button stays disabled until the form is valid.

Key points

  • Import `FormsModule`. Inputs need `ngModel` and a `name` inside a form.
  • `#ref="ngModel"` exposes `valid`, `touched`, and `errors` to the template.
  • HTML attributes like `required` and `minlength` act as validators.
  • Good for small forms. Use reactive forms for complex ones.

Common mistakes

  • Forgetting the `name` attribute, which causes the error that `ngModel` needs a name when inside a form.
  • Showing errors before the user has typed anything.
  • Trying to unit test complex validation through the template.

Follow-ups

  • What does `#f="ngForm"` give you?
  • How is `[(ngModel)]` expanded?
  • How would you add a custom validator to a template-driven input?

Tips

  • Give the sizing rule: small forms here, large forms reactive.
  • Mention touched versus dirty when showing messages.
  • Show the `name` attribute rule. It is the first thing that breaks in practice.

Evaluation rubric

  • Explains NgForm, ngModel, and template variables.
  • Shows validation with touched state.
  • States limits compared with reactive forms.
58.angular-0058Easyfresher

How do you change CSS classes and styles dynamically in Angular, and how do [class.x], [class] and [style] bindings compare with ngClass and ngStyle?

Use [class.name]="condition" for one class, [class]="expression" for several (a string, array, or object), and [style.prop.unit]="value" for styles. ngClass and ngStyle still work but are no longer needed, and Angular recommends the native bindings in new code.

Full answer

There are three levels of class and style binding.

  1. Single class or style: [class.active]="isActive()" adds the class when the value is truthy. [style.width.px]="width()" sets one style, and the unit goes after the property name.
  2. Many classes: [class]="classes()" accepts a string ('a b'), an array (['a', 'b']), or an object ({ a: true, b: false }). Static classes in the same element stay in place, because Angular merges them.
  3. Many styles: [style]="styles()" accepts a string or an object such as { color: 'red', 'font-size.px': 16 }.

ngClass and ngStyle are older directives from CommonModule (now NgClass and NgStyle, standalone). They did what [class] and [style] do today, but need an import and add a small cost. The Angular team recommends the native bindings in new code, and the ngClass and ngStyle directives remain supported for existing templates.

Choose by readability:

  • One or two conditional classes: use [class.x].
  • A computed set: put the logic in a computed and bind [class]="classes()". This keeps the template simple and testable.

Useful details: bindings do not remove classes that are not part of the binding, so unrelated classes from other sources stay. A style value of null removes the style. Class names with special characters such as md:flex work with [class] or [class.md:flex].

Do not build style strings by joining user input, since that can create broken or unsafe CSS.

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

@Component({
  selector: 'app-progress',
  template: `
    <input type="range" min="0" max="100" [value]="percent()" (input)="update($event)" aria-label="Progress" />

    <div class="bar" [class]="barClasses()" [style.width.%]="percent()" [style.min-width.px]="20">
      {{ percent() }}%
    </div>

    <p [class.warn]="percent() < 40" [class.done]="percent() === 100">{{ message() }}</p>
  `,
  styles: `
    .bar { background: #ccc; padding: 4px; }
    .good { background: #9fd49f; }
    .low { background: #f0b4b4; }
    .warn { color: darkorange; }
    .done { color: green; font-weight: bold; }
  `,
})
export class ProgressComponent {
  readonly percent = signal(30);

  readonly barClasses = computed(() => ({ good: this.percent() >= 60, low: this.percent() < 40 }));
  readonly message = computed(() => (this.percent() === 100 ? 'Completed' : 'Keep going'));

  update(event: Event): void {
    this.percent.set(Number((event.target as HTMLInputElement).value));
  }
}

Angular 20.3, strict template check passes. Moving the slider changes the bar width and the status class.

Key points

  • `[class.x]` toggles one class. `[class]` takes a string, array, or object.
  • `[style.prop.unit]` sets one style. `[style]` takes an object.
  • `ngClass` and `ngStyle` are legacy-style directives that still work.
  • A `computed` is the clean place for class logic.

Common mistakes

  • Importing `NgClass` only to toggle one class.
  • Putting long ternary expressions in the template instead of a `computed`.
  • Writing `[style.width]="50"` without the unit, so the browser ignores it.

Follow-ups

  • What happens to static classes when you use `[class]`?
  • How do you remove a style with a binding?
  • Why is `computed` better than a function call in a class binding?

Tips

  • Say which you use today and why, and that you can read `ngClass` code.
  • Remember the unit rule for numeric styles.
  • Keep the logic out of the template.

Evaluation rubric

  • Knows the class and style binding forms.
  • Describes ngClass and ngStyle as older but valid.
  • Uses a computed for complex logic.
59.angular-0059Easyfresher

What are the basic accessibility practices in an Angular app, and how do you apply them in templates?

Start with semantic HTML (button, nav, label), keep keyboard access working, bind ARIA attributes with [attr.aria-*], connect every input to a label, announce dynamic changes, and move focus after navigation. ARIA fills gaps and does not replace native elements.

Full answer

Accessibility means that people using a keyboard, a screen reader, or other assistive tools can use the app. Angular does not make an app accessible by itself, so the practices belong in your templates.

  1. Use native elements. A button is focusable, reacts to Enter and Space, and is announced as a button. A div (click) is none of these. Use a for navigation and button for actions.
  2. Label every field. <label for="email"> with a matching id, or aria-label for an icon button. Placeholders are not labels.
  3. Show errors in a way assistive tools can find: role="alert" or aria-live="polite" on the message, and aria-invalid plus aria-describedby on the input.
  4. ARIA bindings use attribute binding: [attr.aria-expanded]="open()". Property binding does not work for ARIA names such as aria-label.
  5. Keep keyboard focus visible and logical. Do not remove outlines without a replacement. After a route change, move focus to the page heading or announce the new title (the router can set the page title for you).
  6. Announce dynamic updates (a toast, a result count) with a live region. The Angular CDK has LiveAnnouncer for this.
  7. Do not rely on colour only. Text contrast should meet WCAG AA (4.5:1 for normal text).
  8. Images need alt text, or alt="" when decorative.

Tools: the Angular template compiler does not check accessibility, but ESLint rules from angular-eslint (the template accessibility set) catch many mistakes. Test with a keyboard only, then with a screen reader, and run automated checks such as axe in CI.

ARIA rule: first use a native element. Add ARIA only when no native element has the meaning you need.

typescript
import { Component, signal } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-accessible-form',
  imports: [ReactiveFormsModule],
  template: `
    <h1 tabindex="-1">Join the club</h1>

    <label for="name">Full name</label>
    <input
      id="name"
      [formControl]="name"
      [attr.aria-invalid]="name.invalid && name.touched"
      [attr.aria-describedby]="name.invalid && name.touched ? 'name-error' : null"
    />
    @if (name.invalid && name.touched) {
      <p id="name-error" role="alert">Please enter your name.</p>
    }

    <button type="button" [attr.aria-expanded]="open()" aria-controls="help" (click)="open.set(!open())">
      Help
    </button>
    @if (open()) {
      <div id="help">Use your name as it appears on your ID card.</div>
    }

    <button type="button" aria-label="Close dialog">
      <span aria-hidden="true">x</span>
    </button>
  `,
})
export class AccessibleFormComponent {
  readonly name = new FormControl('', { nonNullable: true, validators: [Validators.required] });
  readonly open = signal(false);
}

Angular 20.3, strict template check passes. The error message is linked to the input with `aria-describedby`, and the toggle button reports its state with `aria-expanded`.

Key points

  • Native elements first: `button`, `a`, `label`, `nav`, headings.
  • Bind ARIA with `[attr.aria-*]`. Connect inputs to labels and errors.
  • Manage focus after navigation, and announce dynamic updates.
  • Test with the keyboard and a screen reader. Lint templates for common errors.

Common mistakes

  • Using a clickable `div` instead of a `button`.
  • Binding `[aria-label]` as a property, which does not exist. Use `[attr.aria-label]`.
  • Removing the focus outline for looks and leaving no visible focus style.

Follow-ups

  • How would you announce that a list finished loading?
  • What does `aria-describedby` do on a form field?
  • How do you handle focus when a modal dialog opens and closes?

Tips

  • Say "native first, ARIA second". It is the sentence reviewers expect.
  • Mention keyboard-only testing, which costs nothing.
  • Name `LiveAnnouncer` from the CDK for dynamic announcements.

Evaluation rubric

  • Prefers semantic HTML and labels.
  • Uses attribute binding for ARIA correctly.
  • Mentions focus management and testing.
60.angular-0060Easyfresher

How does routing work in a single-page application, and what is the difference between path (HTML5) and hash location strategies?

In a single-page app the browser loads one HTML page and the Angular router changes the visible components while updating the URL with the History API. The default path strategy gives clean URLs but needs the server to return index.html for unknown paths. The hash strategy keeps the route after a # and needs no server setup.

Full answer

A single-page application (SPA) downloads one HTML file and one set of scripts. When the user clicks a link, the Angular router does not ask the server for a new page. It changes the URL with the browser's History API and shows other components.

Path strategy (default, PathLocationStrategy). URLs look like /courses/42. Because the browser can reload at that URL, the server must be configured to return index.html for any path that is not a real file. If it is not, a reload or a shared link gives a 404 from the server. Angular dev server and most hosting platforms offer a "rewrite to index.html" setting. The <base href="/"> tag in index.html tells the router where the app lives, and must be correct when the app is hosted in a sub folder.

Hash strategy (HashLocationStrategy). URLs look like /#/courses/42. The part after # is never sent to the server, so any static host works without rewrite rules. You enable it with provideRouter(routes, withHashLocation()). The trade-offs: uglier URLs, hash fragments are no longer free for in-page anchors, and search engines handle them poorly.

Which to choose: path strategy for public sites where SEO and clean links matter, with server rewrites. Hash strategy for internal tools or when you cannot control the server.

Related tools: the Location service reads the path and calls back() and forward(), and APP_BASE_HREF sets the base in code. With server-side rendering the server itself handles every route, so the fallback rule is not needed for rendered pages.

typescript
import { Component, inject } from '@angular/core';
import { Location } from '@angular/common';
import { ApplicationConfig } from '@angular/core';
import { Routes, provideRouter, withHashLocation } from '@angular/router';

@Component({
  selector: 'app-home',
  template: `
    <p>Current path: {{ location.path() }}</p>
    <button (click)="location.back()">Back</button>
  `,
})
export class HomeComponent {
  protected readonly location = inject(Location);
}

const routes: Routes = [{ path: 'courses/:id', component: HomeComponent }];

// Path strategy (default): address bar shows /courses/42, server must rewrite to index.html.
export const pathConfig: ApplicationConfig = {
  providers: [provideRouter(routes)],
};

// Hash strategy: address bar shows /#/courses/42, works on any static host.
export const hashConfig: ApplicationConfig = {
  providers: [provideRouter(routes, withHashLocation())],
};

Angular 20.3, type-checked. The URLs in the comments show what the browser address bar would look like in each mode.

Key points

  • An SPA changes components and the URL without full page loads, using the History API.
  • Path strategy needs a server rewrite to `index.html`. Hash strategy does not.
  • Enable hash mode with `withHashLocation()`. Set the base with `<base href>`.
  • Choose path for public, SEO-sensitive sites.

Common mistakes

  • Deploying a path-strategy app to static hosting without a rewrite rule, so refreshing a deep link returns 404.
  • A wrong `<base href>` when hosting in a sub folder, so scripts and routes fail to load.
  • Using the hash strategy and then expecting `#section` anchors to work as before.

Follow-ups

  • How do you host an Angular app in a sub folder?
  • Why does SSR remove the need for the index.html fallback on rendered routes?
  • How does the router know the URL changed when the user presses the back button?

Tips

  • Describe what the server sees in each mode. It makes the difference concrete.
  • Mention the 404-on-refresh symptom, which every Angular developer meets once.
  • Know where the base href lives and why.

Evaluation rubric

  • Explains SPA navigation without page loads.
  • Compares both strategies with server impact.
  • Names the config to switch.