← Interview prep

Angular interview questions

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

195 questions · Page 8 of 10

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

Page 8 of 10

Questions 141–160 of 195 · 0 of 20 on this page marked learned

141.angular-0141Hardsenior

How does the share operator's configuration (connector, resetOnError, resetOnComplete, resetOnRefCountZero) control multicasting, and how does it relate to shareReplay?

share multicasts one subscription to many subscribers through an internal Subject. By default it resets (subscribes again to the source) when the source errors, completes, or the last subscriber leaves. The reset options and the connector let you keep or replay values. shareReplay is share with a ReplaySubject connector and different reset defaults.

Full answer

share() turns a cold source into one that is shared by all current subscribers. Internally it creates a Subject (the connector), subscribes to the source when the first subscriber arrives, and forwards values to every subscriber. The configuration object controls what happens afterwards:

  • connector: () => new Subject() (default): the subject that multicasts. Use () => new ReplaySubject(1) to replay the latest value to late subscribers.
  • resetOnError: true (default): when the source errors, the next subscriber starts a new subscription. Set false to keep the failed state, or pass a function that returns an observable for a delayed reset.
  • resetOnComplete: true (default): when the source completes, a later subscriber starts again. Set false to keep the completed state (late subscribers see only completion, or the replayed values if you use a ReplaySubject).
  • resetOnRefCountZero: true (default): when the last subscriber unsubscribes, the source is unsubscribed and the state is reset. Set false to keep the source running with no listeners, or pass a function, for example () => timer(5000), to keep it alive for a grace period, which avoids restarting during quick navigations.

shareReplay({ bufferSize, refCount }) is a shortcut: share({ connector: () => new ReplaySubject(bufferSize), resetOnError: true, resetOnComplete: false, resetOnRefCountZero: refCount }). So shareReplay(1) keeps the source subscribed after the last subscriber leaves, and keeps the last value after completion, which is what you want for an HTTP result cache.

Choosing:

  • Shared live stream (WebSocket, polling): share(), perhaps with resetOnRefCountZero: () => timer(3000) so a quick route change does not reconnect.
  • Cached HTTP result for the session: shareReplay(1) (source completes, so no leak).
  • Page-level replay without leaks: shareReplay({ bufferSize: 1, refCount: true }).

Remember: sharing hides retries. Put retry before share so all subscribers benefit from one retry loop, and decide where errors should surface.

typescript
import { Observable, ReplaySubject, share, timer } from 'rxjs';

function source(name: string, log: string[]): Observable<number> {
  return new Observable<number>((subscriber) => {
    log.push(`${name}: subscribed`);
    subscriber.next(1);
    return () => log.push(`${name}: torn down`);
  });
}

const log: string[] = [];

const plain$ = source('plain share', log).pipe(share());
const replayed$ = source('replay share', log).pipe(share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false }));
const grace$ = source('grace share', log).pipe(share({ resetOnRefCountZero: () => timer(30) }));

const a = plain$.subscribe();
a.unsubscribe();
plain$.subscribe().unsubscribe(); // source subscribed twice: it reset

const b = replayed$.subscribe();
b.unsubscribe();
replayed$.subscribe().unsubscribe(); // same source subscription is kept

const c = grace$.subscribe();
c.unsubscribe();
grace$.subscribe().unsubscribe(); // within 30 ms: the source is reused

setTimeout(() => {
  console.log(log.join('\n'));
  process.exit(0);
}, 80);

RxJS 7.8. The script was run in Node 24 twice with identical output. It counts subscriptions to the source for three configurations.

Key points

  • `share` multicasts through a Subject and resets on error, complete and zero subscribers by default.
  • `connector` with a `ReplaySubject` replays values. `resetOnRefCountZero` can be a delay function.
  • `shareReplay` is `share` with a ReplaySubject, `resetOnComplete: false` and a `refCount` setting.
  • Put `retry` before `share`.

Common mistakes

  • Assuming `share` replays the latest value to late subscribers.
  • Using `shareReplay(1)` on an endless source and leaking it.
  • Putting `retry` after `share`, so each subscriber retries separately.

Follow-ups

  • How would you keep a WebSocket open for 5 seconds after the last subscriber leaves?
  • What happens to a late subscriber after the source completes in each setting?
  • Why is HTTP a safe case for `shareReplay(1)`?

Tips

  • Write the `shareReplay` equivalent as `share` options. It proves understanding.
  • Mention the grace period option.
  • State where `retry` goes.

Evaluation rubric

  • Explains each share option correctly.
  • Relates shareReplay to share.
  • Chooses configuration for real cases.
142.angular-0142Hardsenior

How does an Observable work internally? Implement a tiny Observable and a map operator to show subscribe, teardown and operator chaining.

An Observable is a function that takes a subscriber and returns a teardown. subscribe calls that function with an observer, and an operator is a function that takes a source Observable and returns a new one that subscribes to the source inside its own subscribe function. Unsubscribing runs the teardown logic of the whole chain.

Full answer

RxJS looks magic, but the core fits in a few lines.

Observable: an object that wraps a function, often called subscribe or the producer. The function receives a subscriber (an object with next, error and complete) and may return a teardown function. Nothing happens until someone calls subscribe(observer). That explains why observables are lazy, and why every subscribe runs the producer again (cold).

Subscriber rules (the "contract"): after error or complete, no more values are delivered, and the teardown runs once. After unsubscribe, values are ignored and the teardown runs.

Operator: a function from Observable to Observable. map(fn) returns source => new Observable(subscriber => source.subscribe({ next: v => subscriber.next(fn(v)), error: e => subscriber.error(e), complete: () => subscriber.complete() })). The returned teardown is the inner subscription's unsubscribe, so cancelling the outer subscription cancels the source. pipe(...ops) just applies the operators in order: ops.reduce((src, op) => op(src), this).

What this teaches:

  • Lazy and cold: no producer runs until subscribe, and each subscriber gets its own run.
  • Chain of teardowns: unsubscribing at the end of a pipeline walks back to the source and clears timers and listeners. This is how switchMap cancels HTTP requests, and why forgetting to unsubscribe from an infinite source leaks.
  • Synchronous by default: of(1,2,3) calls next three times inside subscribe, before it returns.
  • Errors flow down the chain, and operators that do not catch them pass them along.

The real implementation adds a Subscriber class that enforces the contract, Subscription objects that hold several teardowns, operators written with operate helpers, and scheduler support. Understanding the small version makes operators like switchMap easy to reason about: they create inner observables, subscribe, and manage inner teardowns.

typescript
type Teardown = (() => void) | void;

interface Observer<T> {
  next(value: T): void;
  error(err: unknown): void;
  complete(): void;
}

class MiniObservable<T> {
  private readonly producer: (observer: Observer<T>) => Teardown;

  constructor(producer: (observer: Observer<T>) => Teardown) {
    this.producer = producer;
  }

  subscribe(observer: Partial<Observer<T>>): () => void {
    let closed = false;
    let teardown: Teardown;
    const safe: Observer<T> = {
      next: (v) => !closed && observer.next?.(v),
      error: (e) => {
        if (!closed) {
          closed = true;
          observer.error?.(e);
          if (teardown) teardown();
        }
      },
      complete: () => {
        if (!closed) {
          closed = true;
          observer.complete?.();
          if (teardown) teardown();
        }
      },
    };
    teardown = this.producer(safe);
    return () => {
      if (!closed) {
        closed = true;
        if (teardown) teardown();
      }
    };
  }

  pipe<R>(op: (source: MiniObservable<T>) => MiniObservable<R>): MiniObservable<R> {
    return op(this);
  }
}

function map<T, R>(fn: (v: T) => R) {
  return (source: MiniObservable<T>) =>
    new MiniObservable<R>((subscriber) => {
      const unsubscribe = source.subscribe({
        next: (v) => subscriber.next(fn(v)),
        error: (e) => subscriber.error(e),
        complete: () => subscriber.complete(),
      });
      return unsubscribe; // cancelling the outer subscription cancels the source
    });
}

const ticks = new MiniObservable<number>((observer) => {
  let n = 0;
  const id = setInterval(() => observer.next(++n), 10);
  return () => {
    clearInterval(id);
    console.log('source torn down');
  };
});

const cancel = ticks.pipe(map((n) => n * 10)).subscribe({ next: (v) => console.log('value', v) });
setTimeout(() => {
  cancel();
  console.log('unsubscribed');
}, 35);

TypeScript 5.8. The script was run in Node 24 twice with identical output. It is a teaching model, not RxJS code.

Key points

  • An Observable wraps a producer function that receives a subscriber and returns a teardown.
  • Nothing runs until `subscribe`. Each subscribe runs the producer again.
  • An operator wraps a source in a new Observable. Teardowns chain back to the source.
  • The contract: no values after `complete` or `error`, teardown runs once.

Common mistakes

  • Believing an Observable runs when it is created.
  • Forgetting that a custom operator must return the inner teardown.
  • Emitting after `complete` in a hand-written Observable.

Follow-ups

  • How does `switchMap` manage the inner subscription?
  • Why is `of(1,2,3)` synchronous?
  • What does the real `Subscriber` class add?

Tips

  • Live-code the `map` operator. It is short and convincing.
  • State the contract rules.
  • Link teardown chains to cancellation in `switchMap`.

Evaluation rubric

  • Explains the producer, subscriber and teardown model.
  • Implements an operator correctly.
  • Connects it to real behaviour such as cancellation and laziness.
143.angular-0143Hardsenior

How does zone.js make change detection automatic, what are its costs, and how do you migrate an application to zoneless?

zone.js patches browser async APIs so Angular knows when a task finishes and then runs change detection. The costs are extra work for every event and timer, larger bundles, and awkward async await support. Zoneless uses signals, markForCheck and events to schedule updates instead. Migration means making components OnPush compatible, using signals, and removing the zone.js polyfill.

Full answer

How zone.js works: zone.js replaces browser APIs (setTimeout, addEventListener, Promise.then, XMLHttpRequest, and others) with wrapped versions. A zone is an execution context that survives across async calls. NgZone is Angular's zone. When code runs inside it, and its microtask queue becomes empty (onMicrotaskEmpty), Angular runs ApplicationRef.tick(). So any event, timer or HTTP response can update the screen with no extra code.

Costs:

  • Every patched event listener and timer triggers a full pass, even when no state changed (a mouse move listener, a polling timer).
  • Bundle size and start-up work for the patches.
  • Native async/await cannot be patched, so the CLI down-levels async functions to promises. This also blocks some modern features.
  • Third-party libraries run inside the zone and trigger passes unexpectedly, unless wrapped in runOutsideAngular.
  • Stack traces and debugging are harder.

Zoneless: provideZonelessChangeDetection() (stable since Angular 20.2), and remove zone.js from polyfills. Angular then schedules a pass when:

  • a signal read by a template changes,
  • markForCheck is called (also done by the async pipe),
  • a template or host event listener runs,
  • a component is created or destroyed, or a view is attached,
  • ComponentRef.setInput is used.

Migration path:

  1. Make components OnPush compatible. If a component works correctly with OnPush (state changes through signals, inputs, events or async pipe), it works zoneless. This can be done while zone.js is still present.
  2. Replace mutable fields that change in callbacks with signals. Fields changed in setTimeout or a subscription need a signal or markForCheck.
  3. Remove reliance on NgZone.onStable or onMicrotaskEmpty. Use afterNextRender or afterEveryRender.
  4. Use provideZonelessChangeDetection(), remove the polyfill, and fix tests (fixture.whenStable() instead of detectChanges loops, and TestBed.tick() for effects).
  5. Check libraries. Angular Material and CDK support zoneless. Older libraries may need markForCheck wrappers.
  6. Enable provideBrowserGlobalErrorListeners() because zone.js no longer reports unhandled errors for you.

Benefits: smaller bundle, fewer passes, simpler async stack traces, better interoperability with micro-frontends. Risk: silent staleness where data changes but no notification happens. The cure is signals for all UI state.

typescript
import { ApplicationConfig, ChangeDetectionStrategy, Component, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection, signal } from '@angular/core';

export const appConfig: ApplicationConfig = {
  providers: [provideZonelessChangeDetection(), provideBrowserGlobalErrorListeners()],
};

@Component({
  selector: 'app-clock',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>Seconds since open: {{ seconds() }}</p>`,
})
export class ClockComponent {
  readonly seconds = signal(0);

  constructor() {
    // No zone patch is needed. The signal write notifies the scheduler.
    setInterval(() => this.seconds.update((s) => s + 1), 1000);
  }
}

// angular.json: remove "zone.js" from the "polyfills" array of build and test targets.

Angular 20.3, type-checked. The sample shows the zoneless bootstrap and a component that updates through a signal inside a timer. It was not run in a browser here.

Key points

  • zone.js patches async APIs so Angular runs a pass after every task.
  • Costs: extra passes, bundle size, async/await down-leveling, library surprises.
  • Zoneless schedules passes from signals, `markForCheck`, events and view changes.
  • Migrate by making components OnPush compatible and using signals, then remove the polyfill.

Common mistakes

  • Removing zone.js while components still mutate plain fields in callbacks.
  • Relying on `NgZone.onStable` in zoneless mode.
  • Forgetting global error listeners after removing zone.js.

Follow-ups

  • What triggers a pass in zoneless mode?
  • How do tests change with zoneless?
  • Why can code run outside the zone and still update the UI under zoneless?

Tips

  • Describe zone.js as patching, then list costs.
  • Present the migration as OnPush readiness first.
  • Mention error listeners and tests.

Evaluation rubric

  • Explains zone.js mechanics and costs.
  • Lists zoneless triggers correctly.
  • Gives a safe migration plan.
144.angular-0144Hardsenior

How do you decide what to test in an Angular application, and how do unit, component, integration and end-to-end tests fit together?

Many fast unit tests for pure logic and services, a good number of component tests with TestBed and harnesses that check behaviour through the template, a few integration tests with real routing and HTTP mocks, and a small set of end-to-end tests for critical journeys. Test behaviour users see, not private details.

Full answer

Testing strategy is about the return on each test. A common model is a pyramid:

  1. Unit tests (many, fast): pure functions, validators, pipes, reducers, services with simple dependencies. No TestBed needed for pure code. They run in milliseconds and pinpoint failures.
  2. Component tests (a good number): TestBed with the real template. Check what the user sees and does: render the component, set inputs with fixture.componentRef.setInput, click, and assert the DOM. Use component harnesses (HarnessLoader) for Material or your own components, because they hide DOM details and survive refactors. Stub child components or services that call the network. Use provideHttpClientTesting with HttpTestingController and verify() to check requests.
  3. Integration tests (some): several pieces together, for example a routed feature with real guards, a store, and a mocked backend. They find wiring errors that unit tests miss. RouterTestingHarness navigates and returns the component.
  4. End-to-end tests (few): Playwright or Cypress in a real browser against a running app. Cover the money paths (login, enrol, pay). They are slow and flaky if overused, so keep them for high value flows.

Principles:

  • Test behaviour, not implementation. Do not assert on private methods or the exact number of calls unless that is the behaviour.
  • Prefer real objects for cheap collaborators and fakes for slow ones (network, time, storage). Avoid deep mocks that repeat the implementation.
  • Control time: fakeAsync, or vi.useFakeTimers/jasmine.clock.
  • Signals tests: set inputs, call fixture.detectChanges() or await fixture.whenStable(), and use TestBed.tick() for effects.
  • Make tests deterministic: no real network, fixed dates, isolated state per test (TestBed resets between tests).
  • Keep a fast feedback loop: run affected tests on commit, the full suite plus e2e in CI, and track flaky tests.
  • Coverage is a signal, not a goal. 100 percent coverage with no assertions has no value.
  • Accessibility checks with axe in component or e2e tests catch many problems early.

For a school app: a validator for marks is a unit test, the marks form is a component test, "teacher enters marks and a student sees them" is an integration test with a mocked API, and "log in and download report card" is the end-to-end test.

typescript
import { Component, input } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';

@Component({
  selector: 'app-grade-badge',
  template: `<span class="badge">{{ label() }}</span>`,
})
export class GradeBadgeComponent {
  readonly marks = input.required<number>();

  label(): string {
    return this.marks() >= 40 ? 'Pass' : 'Fail';
  }
}

export async function renderBadge(marks: number): Promise<string> {
  await TestBed.configureTestingModule({ imports: [GradeBadgeComponent] }).compileComponents();
  const fixture: ComponentFixture<GradeBadgeComponent> = TestBed.createComponent(GradeBadgeComponent);
  fixture.componentRef.setInput('marks', marks);
  fixture.detectChanges();
  await fixture.whenStable();
  return (fixture.nativeElement as HTMLElement).querySelector('.badge')?.textContent ?? '';
}

// it('shows Pass for 40 marks', async () => expect(await renderBadge(40)).toBe('Pass'));

Angular 20.3. A Karma test runs this component test as written: a grade badge component with an input is rendered, and the DOM text is asserted.

Key points

  • Many unit tests, a good number of component tests, some integration tests, few end-to-end tests.
  • Component tests check DOM behaviour. Harnesses make them stable.
  • Fake slow or random dependencies, control time, and keep tests deterministic.
  • Coverage is a signal, not a goal.

Common mistakes

  • Testing private methods and implementation details.
  • Mocking everything so the test repeats the code.
  • Covering every case with slow end-to-end tests.

Follow-ups

  • When would you use a component harness?
  • How do you test code that uses `setTimeout` or debounce?
  • How do you reduce flaky end-to-end tests?

Tips

  • Use the pyramid and justify it with speed and cost.
  • Give an example from a school app.
  • Say you test behaviour and use harnesses.

Evaluation rubric

  • Describes the levels and their trade-offs.
  • Applies good practices for mocking and time.
  • Chooses tests by value.
145.angular-0145Hardsenior

What is hydration in Angular server-side rendering, what causes hydration mismatch errors, and how do you debug and fix them?

Hydration reuses the server's HTML instead of rebuilding the DOM. Angular walks the existing DOM and matches it to the component tree. A mismatch happens when the server and browser structures differ, usually because of invalid HTML nesting, direct DOM changes, or browser-only values rendered during server rendering. Fix the cause, or use ngSkipHydration for a component as a last resort.

Full answer

Without hydration, the browser shows server HTML and then Angular destroys it and renders again, causing a flash and wasted work. With provideClientHydration(), Angular attaches to the existing DOM nodes, restores state (TransferState for HTTP responses), and makes the page interactive. Angular 19 and later add incremental hydration with @defer (hydrate on viewport), and event replay so clicks before hydration are not lost (withEventReplay()).

How matching works: Angular serializes structure hints in the server HTML (ngh attributes). In the browser, it expects the DOM to have the same nodes in the same order. If a node is missing or different, it throws an error such as NG0500 to NG0502, or NG0503, with a message that names the expected and found nodes.

Common causes:

  1. Invalid HTML nesting, such as a div inside a p or a table without tbody. The browser parser fixes the HTML and changes the structure before Angular sees it.
  2. Direct DOM manipulation (innerHTML, appendChild, document.createElement) in components, or a library that changes the DOM during server rendering. Use renderer APIs or move DOM code to afterNextRender, which runs only in the browser.
  3. Different output on server and client: Date.now(), Math.random(), window.innerWidth, or localStorage read while rendering. The server and browser values differ, so the text or structure differs. Use afterNextRender for browser-only values, or serialize one value with TransferState.
  4. Whitespace changes (preserveWhitespaces) or a CDN that modifies or minifies HTML (for example removing comments, which Angular uses as markers). Disable HTML minification of comments at the edge.
  5. Third-party components that are not hydration safe. Add ngSkipHydration to that component host: <app-chart ngSkipHydration />. It re-renders that subtree only.

Debugging steps:

  • Read the error message: it names the component and the DOM node. Check the HTML in "View Source" (server output) against the DOM after load.
  • Run in development mode, where hydration validates more.
  • Angular DevTools shows hydration status (the overlay highlights hydrated components).
  • Isolate by removing the suspicious component or adding ngSkipHydration temporarily, then fix the real cause.
  • Log isPlatformServer branches that render different content.

Rule: render the same thing on the server and in the first browser pass, and add browser-only differences afterwards.

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

@Component({
  selector: 'app-viewport-info',
  template: `<p>Screen width: {{ width() ?? 'unknown' }}</p>`,
})
export class ViewportInfoComponent {
  // Same value on server and in the first browser render, so hydration matches.
  readonly width = signal<number | null>(null);

  constructor() {
    // Runs only in the browser, after hydration. The DOM updates normally.
    afterNextRender(() => this.width.set(window.innerWidth));
  }
}

// app.config.ts: provideClientHydration(withEventReplay())
// Risky version: {{ innerWidth }} during rendering gives different text on server and browser.

Angular 20.3, type-checked. Server rendering was not run here, so no mismatch was reproduced. The sample shows the safe pattern for browser-only values.

Key points

  • Hydration reuses server DOM instead of rebuilding it, with event replay and incremental hydration options.
  • Mismatches come from invalid HTML, direct DOM changes, and server or client differences.
  • Move browser-only work to `afterNextRender`. Use `TransferState` for shared values.
  • `ngSkipHydration` is a last resort for a component.

Common mistakes

  • Reading `window` or `localStorage` while rendering on the server.
  • Using `ngSkipHydration` everywhere instead of fixing causes.
  • Letting a CDN strip HTML comments that Angular needs.

Follow-ups

  • What does event replay solve?
  • How does `@defer (hydrate on viewport)` reduce work?
  • How would you pass a value from server to browser without a second request?

Tips

  • List the causes in the order you would check them.
  • Mention View Source versus DOM as the first debugging step.
  • Describe `ngSkipHydration` as a temporary tool.

Evaluation rubric

  • Explains hydration and what it saves.
  • Lists realistic mismatch causes.
  • Gives a debugging process and clean fixes.
146.angular-0146Hardsenior

How would you organize a multi-app Angular workspace with shared libraries, and how do tsconfig paths, project references and build order work?

One angular.json workspace holds several applications and libraries. Libraries expose a public API file, and tsconfig paths map import names to source folders so apps import them like packages. Build libraries before apps, enforce import boundaries with lint rules, and use Nx or caching tools for affected builds in large repos.

Full answer

A workspace with several applications (admin, student portal) and shared code needs structure, or it becomes a tangle.

Layout: ng generate application admin and ng generate library ui add projects under projects/ (or apps/ and libs/ in Nx). Each project has its own tsconfigs and entry in angular.json.

Public API: each library has src/public-api.ts that re-exports what other projects may use. Anything not exported is private. Tools like ng-packagr build the library to a package. With secondary entry points (@school/ui/button) consumers can tree shake parts.

Resolution: in tsconfig.json, paths maps names to source: "@school/ui": ["projects/ui/src/public-api.ts"]. Apps import @school/ui in development and the application builder compiles library source together with the app (no pre-build step needed for path-mapped sources). If you publish the library, build it with ng build ui and consumers install the package. With dist mapping ("@school/ui": ["dist/ui"]) apps depend on the built output, so you must build libraries first.

Architecture rules:

  • Layers: apps depend on feature libraries, features depend on UI and data-access libraries, shared utilities depend on nothing. No cycles. Enforce with ESLint @nx/enforce-module-boundaries or eslint-plugin-boundaries and tags.
  • Keep libraries small and focused (feature, ui, data-access, util). Avoid a huge "shared" dump.
  • Do not import another library's internal file paths. Only the public API.
  • One version of Angular and key dependencies for the whole repo, to avoid duplicates.

Tooling for scale: Nx (or Turborepo and similar) gives a task graph, local and remote caching, and affected commands so CI builds only what changed. ng build alone rebuilds the app, but does not know the graph of your libraries for caching.

Pitfalls: circular dependencies between libraries, path mappings that differ between build and test tsconfigs (tests fail to resolve), and libraries importing app code. Keep a shared tsconfig.base.json that other configs extend.

typescript
// file: tsconfig.base.json
{
  "compilerOptions": {
    "strict": true,
    "paths": {
      "@school/ui": ["projects/ui/src/public-api.ts"],
      "@school/ui/button": ["projects/ui/button/src/public-api.ts"],
      "@school/data": ["projects/data/src/public-api.ts"]
    }
  }
}

// file: projects/ui/src/public-api.ts
export * from './lib/card.component';
export * from './lib/modal.service';
// Not exported here means private to the library.

// file: projects/ui/src/lib/card.component.ts
import { Component, input } from '@angular/core';

@Component({ selector: 'ui-card', template: `<h3>{{ title() }}</h3><ng-content />` })
export class CardComponent {
  readonly title = input('');
}

// file: projects/ui/src/lib/modal.service.ts
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ModalService {
  open(name: string): string {
    return `opened ${name}`;
  }
}

The sample is configuration data (a tsconfig base and a library public API). It is type-checked, and the tsconfig file was parsed as JSON. Nothing was built with `ng-packagr` or Nx here.

Key points

  • Apps and libraries are projects in one workspace, each exposing a `public-api.ts`.
  • `tsconfig` `paths` map import names to source or built output.
  • Enforce layers and import boundaries with lint rules. Avoid cycles and a giant shared library.
  • Use Nx or similar for caching and affected builds in large repos.

Common mistakes

  • Importing deep internal files of another library.
  • Creating circular dependencies between libraries.
  • Different `paths` in build and test configs.

Follow-ups

  • How do secondary entry points help tree shaking?
  • When would you publish a library rather than path map it?
  • How do you stop a feature library from importing an app?

Tips

  • Describe layers and tags.
  • Mention public API and boundaries.
  • Say when you would add Nx.

Evaluation rubric

  • Explains workspace structure and path mapping.
  • Covers boundaries and build order.
  • Mentions tooling for scale.
147.angular-0147Hardsenior

A page in your Angular app feels slow. How do you find the cause and decide what to fix first?

Measure first. Reproduce the problem, classify it as load, render or interaction, use Lighthouse and Web Vitals for load, the Chrome Performance panel and Angular DevTools profiler for runtime, and the bundle analyzer for size. Fix the biggest measured cost, then measure again.

Full answer

Guessing wastes time, so follow a loop: measure, find the largest cost, change one thing, measure again.

Step 1: classify the problem.

  • Slow load (white screen, late content): affects LCP and FCP. Tools: Lighthouse, WebPageTest, Chrome DevTools Network panel with throttling, and field data (CrUX or your own Web Vitals reporting).
  • Slow interaction (clicks lag): affects INP. Tool: the Performance panel, which shows long tasks (over 50 ms).
  • Janky scrolling or animation: layout and paint cost. Check the rendering tab and layer counts.

Step 2: find the cause by category.

Load:

  • Large bundles: run ng build --stats-json and open the result in a bundle analyzer (esbuild-visualizer, source-map-explorer). Look for a big library imported for one function, duplicated dependencies, and code that should be lazy (loadComponent, @defer).
  • Slow server or many requests: check the waterfall. Use withFetch, preconnect, HTTP caching, SSR with hydration, and image optimization (NgOptimizedImage, with priority for the LCP image).

Runtime:

  • Too much change detection: Angular DevTools Profiler records each pass and shows which components were checked and how long they took. Fixes: OnPush, signals, moving timers or scroll listeners outside the zone, or going zoneless.
  • Expensive template expressions: methods or heavy pipes called on every pass. Use computed, memoization, or pure pipes.
  • Long lists: track with a stable id in @for, virtual scrolling (cdk-virtual-scroll-viewport), pagination.
  • Heavy computation: move it to a Web Worker or chunk it.
  • Memory growth: Memory panel heap snapshots, detached DOM nodes and unsubscribed streams.

Step 3: prioritise by user impact and effort. A change that saves 800 ms on the main route beats one that saves 20 ms on a rare page.

Step 4: prevent regression: budgets in angular.json, Lighthouse CI on pull requests, and Web Vitals monitoring in production.

You can add your own marks around suspicious code with performance.mark and performance.measure. They appear in the Performance panel timeline and can be logged.

typescript
export function timed<T>(label: string, work: () => T): T {
  performance.mark(`${label}-start`);
  try {
    return work();
  } finally {
    performance.mark(`${label}-end`);
    const entry = performance.measure(label, `${label}-start`, `${label}-end`);
    console.log(label, entry.duration >= 0 ? 'measured' : 'invalid');
  }
}

const total = timed('sum-marks', () => {
  let sum = 0;
  for (let i = 0; i < 1_000_000; i++) {
    sum += i % 100;
  }
  return sum;
});
console.log('total', total);

TypeScript 5.8. The helper that wraps `performance.mark` and `performance.measure` was run in Node 24 twice. The measured times differ between runs, so the script prints only the label and whether the duration was non-negative, and both runs were identical.

Key points

  • Measure, change one thing, measure again.
  • Classify as load, interaction or jank, and choose tools for each.
  • Common fixes: lazy loading, smaller bundles, OnPush and signals, `track`, virtual scroll, workers.
  • Prevent regressions with budgets and monitoring.

Common mistakes

  • Optimising without a measurement.
  • Fixing a small cost on a rarely used page first.
  • Profiling a development build, which is slower and different from production.

Follow-ups

  • How do you reduce INP in a heavy form?
  • When would you use a Web Worker?
  • How would you catch a regression in CI?

Tips

  • Start with classification. It shows a method.
  • Use production builds for measurements.
  • Finish with prevention.

Evaluation rubric

  • Gives a measurement-led workflow.
  • Matches tools and fixes to problem types.
  • Prioritises and prevents regressions.
148.angular-0148Hardsenior

How do typed reactive forms work, and how would you write a small helper that builds a typed FormGroup and extracts the typed value?

Typed forms infer control types from FormControl and FormGroup. new FormControl('') is string or null because reset sets null, so use nonNullable to get string. value is Partial because disabled controls are left out, and getRawValue gives the full type. A generic helper can build a form from a model with types preserved.

Full answer

Since Angular 14, FormControl<T>, FormGroup<{...}> and FormArray<T> carry types.

Key rules:

  1. new FormControl('') has type FormControl<string | null>, because reset() sets the value to null. Use new FormControl('', { nonNullable: true }) so reset goes back to the initial value, and the type is string. FormBuilder.nonNullable.group({...}) applies this to all controls.
  2. group.value has type Partial<{...}>, because disabled controls are not included. group.getRawValue() includes disabled controls and has the full type.
  3. form.controls.name is typed, and a wrong name is a compile error. form.get('name') is typed for simple paths in newer versions, but controls is clearer.
  4. FormRecord<T> is for dynamic keys with the same type. FormArray<FormControl<string>> for lists.
  5. UntypedFormGroup exists for migration only.

A helper: give a plain model ({ name: string; marks: number }) and get a typed form where each property is a non-nullable control:

type ControlsOf<T> = { [K in keyof T]: FormControl<T[K]> }

function formFor<T extends Record<string, unknown>>(model: T): FormGroup<ControlsOf<T>> creates a FormControl(value, { nonNullable: true }) for each key. This keeps types in one place and avoids repeating them.

Limits: nested groups and arrays need recursive types, which makes types hard to read. For nested forms, build small typed sub forms and compose them. Do not make the type too clever, because error messages become hard to read for the team.

Submit pattern: if (form.invalid) return; const value = form.getRawValue(); gives a fully typed object to send to the server. Map to a DTO type explicitly, so form shape changes do not silently change the API.

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

type ControlsOf<T> = { [K in keyof T]: FormControl<T[K]> };

export function formFor<T extends Record<string, string | number | boolean>>(model: T): FormGroup<ControlsOf<T>> {
  const controls = {} as ControlsOf<T>;
  for (const key of Object.keys(model) as (keyof T)[]) {
    controls[key] = new FormControl(model[key], { nonNullable: true }) as ControlsOf<T>[keyof T];
  }
  return new FormGroup(controls);
}

interface StudentModel extends Record<string, string | number | boolean> {
  name: string;
  marks: number;
}

const form = formFor<StudentModel>({ name: 'Asha', marks: 72 });
const marks: number = form.controls.marks.value; // number, not number | null
const raw: StudentModel = form.getRawValue(); // full type, includes disabled controls
// form.controls.age;  // compile error: no such control
form.controls.marks.disable();
const partial: Partial<StudentModel> = form.value; // marks is missing at run time
console.log(marks, raw, partial);

Angular 20.3 strict mode, type-checked with `ngc`. The assignments in the example are checked by the compiler. The helper itself was not unit tested.

Key points

  • `FormControl<string | null>` by default. Use `nonNullable` to get `string` and keep the initial value on reset.
  • `value` is Partial because of disabled controls. `getRawValue()` is the full type.
  • A mapped type `ControlsOf<T>` plus a helper builds typed forms from a model.
  • Keep types simple. Map form values to a DTO explicitly.

Common mistakes

  • Forgetting `nonNullable` and getting `null` after reset.
  • Using `value` and expecting all keys.
  • Using `UntypedFormGroup` to avoid type errors.

Follow-ups

  • What is the difference between `FormRecord` and `FormGroup`?
  • How would you type a nested group?
  • Why map the form value to a DTO?

Tips

  • Explain the reset to null reason.
  • Show the mapped type.
  • Say you keep types readable.

Evaluation rubric

  • Explains null handling, Partial value and getRawValue.
  • Writes a correct generic helper.
  • Gives practical typing advice.
149.angular-0149Hardsenior

How do you write a custom UrlMatcher and a custom UrlSerializer, and when are they needed?

A UrlMatcher decides whether a route matches the URL segments and returns the consumed segments and named params, for patterns like "@username" that a path string cannot express. A UrlSerializer parses and writes whole URLs, so a custom one can normalise case or handle legacy formats. Both are rarely needed, so use them when path patterns are not enough.

Full answer

Path strings such as courses/:id cover most routes. Two extension points handle the rest.

UrlMatcher (per route): a function (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult | null. Return null for no match. Return { consumed: segments, posParams: { name: segments[0] } } to match and expose parameters. Use it for:

  • Profile URLs like /@asha (a path cannot match a prefix of a segment).
  • Matching by rules, such as a numeric id versus a slug.
  • Migrating old URL shapes without redirects.

Register with { matcher: profileMatcher, component: ProfileComponent }. The params are read in the component like any route param. Test matchers as plain functions, since they need no router.

UrlSerializer (global): the service that turns a URL string into a UrlTree (parse) and back (serialize). Replace it by providing { provide: UrlSerializer, useClass: LowerCaseUrlSerializer }. Extend DefaultUrlSerializer, and override parse to normalise the path (lowercase it, remove trailing slashes), so /Courses/42/ and /courses/42 reach the same route. Cases for it: case insensitive URLs, legacy query formats, custom encodings, or stripping tracking parameters.

Cautions:

  • A global serializer affects every URL, including query params and fragments. Only lowercase the path part, because params can be case sensitive (ids, tokens).
  • Redirects (server side) are better than rewriting for SEO. A serializer changes the URL the router uses internally, and the browser address bar follows serialize.
  • Keep parse(serialize(tree)) stable. Round trips must not change the tree, or navigation can loop.
  • Prefer simple solutions first: redirectTo, canMatch, and route data.

Testing: matchers are pure. For the serializer, call parse with sample strings and assert on the resulting tree.

typescript
import { Injectable } from '@angular/core';
import { DefaultUrlSerializer, UrlMatchResult, UrlSegment, UrlSerializer, UrlTree } from '@angular/router';

export function profileMatcher(segments: UrlSegment[]): UrlMatchResult | null {
  if (segments.length === 1 && segments[0].path.startsWith('@') && segments[0].path.length > 1) {
    return {
      consumed: segments,
      posParams: { username: new UrlSegment(segments[0].path.slice(1), {}) },
    };
  }
  return null;
}

@Injectable()
export class LowerCasePathSerializer extends DefaultUrlSerializer {
  override parse(url: string): UrlTree {
    const queryStart = url.search(/[?#]/);
    const path = queryStart === -1 ? url : url.slice(0, queryStart);
    const rest = queryStart === -1 ? '' : url.slice(queryStart);
    const cleanPath = path.length > 1 ? path.replace(/\/+$/, '') : path;
    return super.parse(cleanPath.toLowerCase() + rest);
  }
}

// { matcher: profileMatcher, component: ProfileComponent }
// providers: [{ provide: UrlSerializer, useClass: LowerCasePathSerializer }]

Angular 20.3. A Karma test calls the matcher with segments, and parses `/Courses/42/` with the serializer, checking the lowercase path and untouched query case.

Key points

  • `UrlMatcher` matches segments and returns consumed segments and `posParams`, or `null`.
  • `UrlSerializer` parses and writes URLs globally. Extend `DefaultUrlSerializer`.
  • Normalise only the path. Keep round trips stable.
  • Try `redirectTo` and `canMatch` first.

Common mistakes

  • Lowercasing query parameters or fragments in a global serializer.
  • Returning segments that were not consumed.
  • Writing a serializer whose parse and serialize are not inverses.

Follow-ups

  • How would you match `/@username` URLs?
  • Why can a serializer cause navigation loops?
  • When is a server redirect better?

Tips

  • Show the `@username` matcher. It is a classic.
  • Warn about query parameters.
  • Mention testing the pure functions.

Evaluation rubric

  • Implements matcher and serializer correctly.
  • Understands the global effect and risks.
  • Chooses simpler tools first when they fit.
150.angular-0150Hardsenior

Write an HTTP interceptor that caches GET responses for a short time and shares one request among simultaneous callers.

Keep a Map from URL to a shared observable and an expiry time. For a GET without a no-cache flag, return the stored observable if it is fresh, otherwise forward the request with shareReplay(1) and store it. Remove failed requests so errors are not cached, and clear the cache when a write request succeeds.

Full answer

Many components ask for the same data (the course list in the header and on the page). Without care, each asks the server. An interceptor can fix this once.

Design:

  1. Only handle GET. Pass everything else through. After a successful write (POST, PUT, PATCH, DELETE), clear the cache, because the data may have changed.
  2. Key: req.urlWithParams. Add the headers that change the response (language, authorization) to the key if they matter, or the cache would leak data between users. Clear the cache on logout.
  3. Entry: { expires: number, response$: Observable<HttpEvent> }. If an entry exists and is fresh, return its response$. Because response$ uses shareReplay(1), callers that arrive while the request is still running share it (deduplication), and later callers within the time to live get the replayed response (caching).
  4. Errors: if the request errors, delete the entry (catchError or tap({ error })), so the next call tries again.
  5. Opt out: a custom HttpContextToken (NO_CACHE) lets a call skip the cache, for example a "refresh" button.
  6. Time to live: short, such as 30 seconds, for data that changes slowly. Use Date.now() or an injectable clock for tests.
  7. HttpClient returns events: with shareReplay(1) on the interceptor output you replay the last event, which is the HttpResponse (the Sent event is not delivered by default). Use filter carefully if you track progress events, and do not cache requests that use reportProgress.

Memory: limit entry count or remove expired entries when you read or write.

Alternatives: httpResource and TanStack Query handle caching at the data layer, and the browser HTTP cache handles it with headers (Cache-Control). Use an interceptor when the server cannot send good cache headers, or when you also need deduplication.

Testing: use HttpTestingController. Two calls to the same URL should produce one request, the second after the TTL should produce another, and an error should not be cached.

typescript
import { HttpContextToken, HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { Observable, shareReplay, tap } from 'rxjs';

export const NO_CACHE = new HttpContextToken<boolean>(() => false);

interface Entry {
  expires: number;
  response$: Observable<HttpEvent<unknown>>;
}

const TTL_MS = 30_000;
const cache = new Map<string, Entry>();

export function clearHttpCache(): void {
  cache.clear();
}

export const cacheInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next) => {
  if (req.method !== 'GET') {
    return next(req).pipe(tap({ next: (e) => e.type !== 0 && cache.clear() }));
  }
  if (req.context.get(NO_CACHE)) {
    return next(req);
  }

  const key = req.urlWithParams;
  const hit = cache.get(key);
  if (hit && hit.expires > Date.now()) {
    return hit.response$;
  }

  const response$ = next(req).pipe(
    tap({ error: () => cache.delete(key) }),
    shareReplay(1),
  );
  cache.set(key, { expires: Date.now() + TTL_MS, response$ });
  return response$;
};

Angular 20.3. A Karma test with `HttpTestingController` checks that two simultaneous GETs make one request, and that a failed request is retried on the next call.

Key points

  • Cache only GET. Key by URL with params. Clear the cache after writes and on logout.
  • Store a `shareReplay(1)` observable per key with an expiry. It deduplicates and caches.
  • Delete entries on error. Offer a `NO_CACHE` context token.
  • Keep a short time to live and limit the size.

Common mistakes

  • Caching error responses.
  • Sharing cached data between different users.
  • Never clearing the cache after a write.

Follow-ups

  • How would you add stale-while-revalidate?
  • How does this differ from `httpResource`?
  • How would you bound the cache size?

Tips

  • Mention both deduplication and caching.
  • Say you clear on write and logout.
  • Point out the user data leak risk.

Evaluation rubric

  • Implements dedup and TTL cache correctly.
  • Handles errors, writes and opt-out.
  • Considers security and memory.
151.angular-0151Easyfresher

What is a decorator in Angular, what metadata does @Component carry, and how does Angular use it?

A decorator is a function written with @ above a class, property or method. Angular decorators such as @Component, @Injectable, @Directive and @Pipe attach metadata (selector, template, imports, providers) that the Angular compiler reads to know how to build and use the class.

Full answer

A decorator is a special function that you write with an @ sign directly above a class, a property, a method or a parameter. It adds information to the thing it decorates, or changes it. Decorators are a TypeScript feature, and Angular uses them to attach metadata to your code.

Metadata means data about the class. A plain class StudentCardComponent is only a TypeScript class. The decorator @Component({ ... }) tells Angular that it is a component, and describes it:

  • selector: the tag name used in templates, such as app-student-card.
  • template or templateUrl: the HTML of the component.
  • styles or styleUrl: the CSS that belongs to it.
  • imports: the other components, directives and pipes used in the template.
  • providers: services created for this component.
  • changeDetection: Default or OnPush.
  • host: bindings and listeners on the host element.

The other main class decorators are @Injectable (a service that can be injected), @Directive (behaviour for an element), @Pipe (a transform for templates) and @NgModule (legacy modules). Older code also uses property decorators: @Input, @Output, @ViewChild, @HostBinding, @HostListener. In new code, input(), output(), viewChild() and the host metadata replace most of them.

How Angular uses it: during the build, the Angular compiler reads the decorator and generates static definition code (such as the component definition with its template function) on the class. This is the ahead-of-time (AOT) compile. At run time Angular uses that generated code, not the decorator call itself. This is also why the metadata must be written in a way the compiler can read, for example plain object literals.

A decorator that you write yourself is just a function that receives the class (or the member). Angular does not need it, but it shows the idea: a function that runs once when the class is defined.

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

// A decorator is a function. This one runs once when the class is defined.
export function Tag(label: string) {
  return (target: { tag?: string }): void => {
    target.tag = label; // a static property on the class
  };
}

@Injectable({ providedIn: 'root' })
export class MarksService {
  total(marks: number[]): number {
    return marks.reduce((sum, m) => sum + m, 0);
  }
}

@Tag('student-card')
@Component({
  selector: 'app-student-card',
  template: `<p>{{ name }} scored {{ total }}</p>`,
  styles: [`p { margin: 0; }`],
})
export class StudentCardComponent {
  static tag?: string;
  name = 'Asha';
  total = new MarksService().total([40, 35, 20]);
}

Angular 20.3 with `experimentalDecorators` enabled (the Angular CLI default), type-checked. A Karma test checks the custom decorator effect and that the component renders its template.

Key points

  • A decorator is a function used with `@` above a class, property or method.
  • Angular decorators carry metadata: selector, template, imports, providers and more.
  • The compiler turns the metadata into generated definitions on the class.
  • Property decorators like `@Input` have signal-based replacements such as `input()`.

Common mistakes

  • Forgetting the decorator and expecting a plain class to work as a component or service.
  • Putting a component in `imports` without it being standalone.
  • Writing metadata with values that the compiler cannot read at build time.

Follow-ups

  • What is the difference between a decorator and a TypeScript class?
  • Why does Angular generate code from decorators at build time?
  • Which decorators have signal based replacements?

Tips

  • Say "metadata" and list four fields from memory.
  • Mention that the AOT compiler reads the decorator.
  • Show awareness that newer APIs reduce decorator use.

Evaluation rubric

  • Defines a decorator correctly.
  • Lists common decorators and metadata fields.
  • Explains the build time role.
152.angular-0152Easyfresher

What is the $event object in an Angular event binding, and how do you use it for keyboard events, typed targets and preventing default actions?

In (event)="handler($event)", $event is the DOM event object (or the emitted value for a component output). Use key filters like (keyup.enter), read the element from event.target with a type cast, and call preventDefault or stopPropagation when the browser default or bubbling should not happen.

Full answer

When you write (click)="save($event)", Angular listens to the browser event and passes the event object as $event. For native DOM events it is the same object you get from addEventListener: a MouseEvent, KeyboardEvent, InputEvent, SubmitEvent, and so on. For a component output, $event is whatever the child emitted, for example a number or an object.

Useful patterns:

  1. Key filters. (keyup.enter)="add()" runs only when Enter is pressed, and (keydown.escape)="close()", (keydown.control.s)="save()" work in the same way. This is simpler than reading event.key yourself.
  2. Reading the value. event.target has the type EventTarget | null, so TypeScript does not know about .value. Put the conversion in a small method: onInput(event: Event) { const input = event.target as HTMLInputElement; this.name.set(input.value); }. A template reference variable is an alternative: <input #box (input)="name.set(box.value)" />.
  3. Default actions. A link or form has a built-in action. event.preventDefault() stops it. With (ngSubmit) on a form, Angular already prevents the page reload.
  4. Bubbling. Events travel from the inner element to its parents. event.stopPropagation() stops the event before it reaches parent handlers. Use it sparingly, because it hides events from other code. In a table row with a delete button, stopping propagation prevents the row click from also firing.
  5. Several statements. (click)="count = count + 1; log($event)" is allowed, but a method is easier to read and test.

Each handler call is followed by change detection, so the screen updates. Avoid heavy work in handlers that run often, such as mousemove and scroll. Debounce them, or run them outside Angular.

Typing: write handler parameters with the specific type (KeyboardEvent, MouseEvent). With strictTemplates, the compiler checks that $event matches what the handler expects.

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

@Component({
  selector: 'app-todo-list',
  template: `
    <input #box aria-label="New task" (keyup.enter)="add(box)" (input)="onInput($event)" />
    <p>Typing: {{ typing() }}</p>
    <ul>
      @for (task of tasks(); track task) {
        <li (click)="rowClicks.set(rowClicks() + 1)">
          {{ task }}
          <button type="button" (click)="remove(task, $event)">Delete</button>
        </li>
      }
    </ul>
    <a href="/help" (click)="openHelp($event)">Help</a>
  `,
})
export class TodoListComponent {
  readonly tasks = signal<string[]>([]);
  readonly typing = signal('');
  readonly rowClicks = signal(0);
  defaultPrevented = false;

  onInput(event: Event): void {
    this.typing.set((event.target as HTMLInputElement).value);
  }

  add(box: HTMLInputElement): void {
    const text = box.value.trim();
    if (text) {
      this.tasks.update((list) => [...list, text]);
      box.value = '';
      this.typing.set('');
    }
  }

  remove(task: string, event: MouseEvent): void {
    event.stopPropagation(); // the row click handler must not run too
    this.tasks.update((list) => list.filter((t) => t !== task));
  }

  openHelp(event: MouseEvent): void {
    event.preventDefault(); // stay on the page
    this.defaultPrevented = event.defaultPrevented;
  }
}

Angular 20.3, strict template check passes. A Karma test sends an Enter keyup, a click on a button inside a row, and checks the list, that the row click does not fire, and that the link default action is prevented.

Key points

  • `$event` is the native event for DOM events, or the emitted value for outputs.
  • Use key filters such as `(keyup.enter)`. Cast `event.target` to the element type to read its value.
  • `preventDefault` stops the browser action. `stopPropagation` stops bubbling.
  • Avoid heavy work in frequent event handlers.

Common mistakes

  • Reading `event.target.value` without a cast and fighting the compiler.
  • Using `stopPropagation` everywhere and breaking other listeners.
  • Calling `preventDefault` on `ngSubmit` when Angular already does it.

Follow-ups

  • What is `$event` for a component output?
  • How would you handle a keyboard shortcut like Ctrl+S?
  • How do you stop a row click when a button inside the row is clicked?

Tips

  • Show a typed handler and not `$any($event)`.
  • Mention key filters. Many candidates forget them.
  • Explain bubbling with the table row example.

Evaluation rubric

  • Explains `$event` for both DOM events and outputs.
  • Handles typing and key filters correctly.
  • Understands default action and bubbling.
153.angular-0153Easyfresher

How do the built-in date, currency, number and percent pipes format values, and what are the common gotchas with date format letters, time zones and locale?

The built-in pipes format values for display using the app locale. DatePipe uses format letters where MM is month and mm is minutes, it converts to the browser time zone unless you pass one, and CurrencyPipe, DecimalPipe and PercentPipe take a format string like 1.2-2. Unsupported locales need registerLocaleData.

Full answer

Pipes transform a value for display only. The data in your class does not change. The four formatting pipes that every fresher meets:

  1. date: {{ exam | date:'dd MMM yyyy' }}. Presets exist: short, medium, longDate, shortTime. The main gotchas are the letters. MM is month and mm is minutes. yyyy is the year and YYYY is the week-based year, which gives wrong results near new year. HH is 24 hour and hh is 12 hour (add a for AM or PM).
  2. currency: {{ fee | currency:'INR' }} shows the symbol for the locale, and currency:'USD':'code' shows the code. The default fraction digits depend on the currency.
  3. number (decimal): {{ avg | number:'1.1-2' }} means at least 1 integer digit, and 1 to 2 fraction digits. The value is rounded, not cut.
  4. percent: {{ ratio | percent }}. It multiplies by 100, so pass 0.85 to get 85 percent, not 85.

Time zone gotcha. The date pipe converts a date to the browser's time zone unless you pass a third argument, for example date:'short':'UTC'. new Date('2026-12-04') is UTC midnight in JavaScript, so a user west of UTC who shows it with the date pipe sees 3 December. (If you pass the plain string '2026-12-04' to the pipe, Angular reads it as a local date, which hides the problem until the value goes through new Date.) Store full ISO timestamps and decide the display zone on purpose.

Locale gotcha. The default locale is en-US. Formats, month names and separators change with the locale. To use another locale, provide LOCALE_ID and register the data: registerLocaleData(localeHi) from @angular/common/locales/hi. Without the registered data Angular throws an error that the locale is missing.

Other points: a pipe call in a template is cheap because built-in pipes are pure (they run again only when the input reference changes). A null or undefined input returns null and prints nothing. For custom needs use Intl.DateTimeFormat in a computed value.

typescript
import { formatDate, formatNumber, formatPercent, formatCurrency } from '@angular/common';

const exam = new Date(Date.UTC(2026, 11, 4, 15, 5, 0)); // 4 Dec 2026, 15:05 UTC

export function samples(): string[] {
  return [
    formatDate(exam, 'dd MMM yyyy', 'en-US', 'UTC'),
    formatDate(exam, 'MM/dd HH:mm', 'en-US', 'UTC'),
    formatDate(exam, 'hh:mm a', 'en-US', 'UTC'),
    formatDate(exam, 'shortTime', 'en-US', '+0530'),
    formatNumber(3.14159, 'en-US', '1.1-2'),
    formatPercent(0.856, 'en-US', '1.0-0'),
    formatCurrency(1500, 'en-US', '$', 'USD', '1.2-2'),
  ];
}
// The same functions power the pipes: {{ exam | date:'dd MMM yyyy':'UTC' }}

Angular 20.3 with the default en-US locale. The formatting calls were run in a Karma test in headless Chrome, and the outputs in the comments are the ones captured there.

Key points

  • Pipes format for display only. The data does not change.
  • Date letters: `MM` month, `mm` minutes, `yyyy` year, `HH` 24-hour. `YYYY` is a trap.
  • `percent` multiplies by 100. `number:'1.1-2'` sets integer and fraction digits.
  • Dates show in the browser time zone unless you pass one. Other locales need `registerLocaleData`.

Common mistakes

  • Using `mm` for month or `YYYY` for year.
  • Passing `85` to the percent pipe and getting 8500 percent.
  • Building a `Date` from a date-only string and showing it in a time zone west of UTC.

Follow-ups

  • How would you show a date in a fixed time zone?
  • What does `1.2-2` mean in the number pipe?
  • How do you add the Hindi locale?

Tips

  • Show the `MM` versus `mm` mistake. Interviewers like it.
  • Mention time zones without being asked.
  • Say that built-in pipes are pure.

Evaluation rubric

  • Explains each pipe with correct format syntax.
  • Knows the date letter, zone and locale traps.
  • Understands that pipes only change display.
154.angular-0154Easyfresher

What belongs in a component and what belongs in a service? Give examples from a school app.

A component owns the screen: its template, the user's input and view-only state. A service owns logic and data that is not about one screen: HTTP calls, shared state, business rules and helpers. Keeping them apart makes code reusable, testable and easier to change.

Full answer

A component answers the question "what does this part of the screen look like and what does the user do here?" A service answers "how does the app get, keep or calculate this data?"

Put in the component:

  • The template and styles.
  • Reading input from the user (clicks, typing) and calling a method for it.
  • State that only this screen needs, such as "is the menu open" or "which tab is active".
  • Simple formatting for display.

Put in a service:

  • HTTP calls: getStudents(), saveMarks().
  • Data that several components share, such as the logged in user or the selected class. A service with signals works as a small store.
  • Business rules, such as how to calculate a grade or whether a student can enrol. These do not depend on any screen.
  • Wrappers for browser APIs (localStorage, window), so tests and server rendering can replace them.

Why split:

  1. Reuse. The marks page and the report page can both use MarksService.
  2. Testing. A calculation in a service is a plain class test. A calculation inside a component needs a rendered component.
  3. Lifetime. A component is created and destroyed as the user moves around. A service in providedIn: 'root' lives as long as the app, so data survives navigation.
  4. Readability. A component with 600 lines mixes HTTP, rules and markup. Small components are easier to read.

Do not go too far in the other direction: a service for every tiny helper, or state placed in a service when only one component uses it, adds files and no value. A good rule is to start in the component, and move code to a service when a second place needs it or when it has no relation to the view.

A service is created through dependency injection: inject(MarksService). The component never uses new MarksService().

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

@Injectable({ providedIn: 'root' })
export class GradeService {
  readonly selectedClass = signal('10A'); // shared state

  grade(marks: number): string {
    if (marks >= 75) return 'A';
    if (marks >= 50) return 'B';
    return marks >= 35 ? 'C' : 'Fail';
  }
}

@Component({
  selector: 'app-marks-row',
  template: `<p>{{ name }}: {{ marks }} ({{ grades.grade(marks) }}) in class {{ grades.selectedClass() }}</p>`,
})
export class MarksRowComponent {
  protected readonly grades = inject(GradeService);
  name = 'Asha';
  marks = 82;
}

@Component({
  selector: 'app-class-picker',
  template: `<button type="button" (click)="grades.selectedClass.set('10B')">Switch to 10B</button>`,
})
export class ClassPickerComponent {
  protected readonly grades = inject(GradeService);
}

Angular 20.3, strict template check passes. A Karma test injects the service in the component and checks the grade text and that two components see the same shared value.

Key points

  • Components own the view and user interaction. Services own data access, shared state and business rules.
  • A root service lives as long as the app, so its data survives navigation.
  • Splitting gives reuse, easier tests and smaller components.
  • Start in the component and extract when a second use appears.

Common mistakes

  • Making HTTP calls and grade rules inside the component.
  • Creating a service with `new` instead of injecting it.
  • Moving every small thing into a service without need.

Follow-ups

  • Where would you keep the logged in user?
  • How does a service share state between two sibling components?
  • Why is a calculation easier to test in a service?

Tips

  • Use two concrete school examples.
  • Mention lifetime and testing as the reasons.
  • Say you extract when needed and do not over-split.

Evaluation rubric

  • Gives a clear rule for the split.
  • Lists reasons: reuse, testing, lifetime.
  • Warns against over-engineering.
155.angular-0155Easyfresher

What do the RxJS operators map, filter and tap do, and how do they differ when you build a pipe?

map changes each value, filter lets only matching values through, and tap runs a side effect (such as logging) without changing the value. They are used inside pipe(), run in order for each value, and an observable does nothing until someone subscribes.

Full answer

An operator is a function that you put inside pipe(...). Each operator takes the values from the step before and gives values to the step after. The three most common ones:

  • map(fn) transforms every value. map(m => m + 5) turns 40 into 45. The output has the same number of values as the input.
  • filter(predicate) keeps only the values for which the predicate returns true. The output can have fewer values. Values that fail are dropped, and the stream goes on.
  • tap(fn) runs a side effect, such as console.log, setting a loading flag or saving to a cache. The value passes through unchanged. It is the right tool for debugging a pipe: put tap(v => console.log('after map', v)) between two steps.

Order matters. filter before map means less work, because you only transform what you keep. map before filter lets you filter on the transformed value. In the example below, marks are first curved with map, and then filter keeps passing marks.

Important points:

  1. Nothing happens until subscribe. The pipe describes the work. Subscribing starts it.
  2. Each subscription runs the pipe again for a cold source.
  3. Operators do not change the original observable. pipe returns a new one.
  4. Keep map pure. Doing side effects in map makes code hard to follow, so use tap for them.
  5. tap also accepts an observer object, tap({ next, error, complete }), so you can log errors and completion.

Array methods map and filter have the same idea, but an array method works on all items at once, while an RxJS operator works on one item at a time as it arrives over time.

typescript
import { from, filter, map, tap } from 'rxjs';

const marks$ = from([28, 45, 33, 71, 90]);

const curved$ = marks$.pipe(
  tap((m) => console.log('raw', m)),
  map((m) => m + 5), // curve: add five marks
  filter((m) => m >= 35), // keep passing marks only
  tap((m) => console.log('passing', m)),
);

console.log('before subscribe: nothing has run');
curved$.subscribe({
  next: (m) => console.log('received', m),
  complete: () => console.log('done'),
});

RxJS 7.8. The script was run in Node 24 twice with identical output.

Key points

  • `map` transforms, `filter` drops values, `tap` runs side effects and leaves the value alone.
  • They run in pipe order for each value. Nothing runs until `subscribe`.
  • Use `tap` for logging and flags, not `map`.
  • `filter` early to reduce work.

Common mistakes

  • Expecting output without subscribing.
  • Doing side effects inside `map`.
  • Forgetting that `filter` drops values silently.

Follow-ups

  • What is the difference between the array `map` and the RxJS `map`?
  • How would you log an error in a pipe without handling it?
  • Does `tap` change the value?

Tips

  • Show a pipe with all three and the log output.
  • Say that `pipe` returns a new observable.
  • Mention subscribing.

Evaluation rubric

  • Describes each operator correctly.
  • Understands ordering and laziness.
  • Uses `tap` for side effects.
156.angular-0156Easyfresher

Which TypeScript features do Angular developers use every day, and why does Angular use TypeScript?

Angular is written in TypeScript. Static types catch mistakes at build time, interfaces describe data shapes, generics keep services and components type safe, union and literal types model fixed choices, and strict mode makes the compiler check null and undefined. Browsers run the compiled JavaScript.

Full answer

TypeScript is JavaScript with types. The compiler checks the types while you build, then removes them and produces plain JavaScript that the browser runs. Angular chose it because large apps need help: editors can autocomplete, refactoring is safe, and many mistakes appear as red lines and not as bugs in production. Decorators, which Angular uses for metadata, are also part of the TypeScript ecosystem.

Features used every day:

  1. Basic types and inference: let marks: number = 80; and const name = 'Asha' (TypeScript infers string). Prefer inference when the type is obvious.
  2. Interfaces and type aliases describe the shape of data from an API: interface Student { id: number; name: string; email?: string }. The ? means optional.
  3. Generics: signal<Student[]>([]), HttpClient.get<Student[]>(url), Observable<number>. The type in < > tells the tool what the container holds.
  4. Union and literal types: type Status = 'pending' | 'paid' allows only those two strings. This replaces many enums and removes typing mistakes.
  5. Enums: still possible, but string literal unions are lighter and tree-shake better.
  6. Access modifiers: private, protected, readonly. In templates, members must not be private, so use protected for template-only members.
  7. Strict mode ("strict": true): turns on strictNullChecks, so Student | undefined must be checked before use. Angular projects use it by default, and strictTemplates applies the same checking to templates.
  8. Optional chaining and nullish coalescing: student?.name ?? 'Unknown'.
  9. Type guards and narrowing: if (typeof value === 'string') lets TypeScript treat the value as a string inside the block.

A caution: types exist only at build time. A response from the server is not checked at run time, so get<Student[]> is a promise to the compiler and not a validation. If the data is untrusted, validate it.

any turns the checks off. Use unknown and narrow, or write the real type.

typescript
export {};

interface Student {
  id: number;
  name: string;
  email?: string; // optional
}

type Status = 'pending' | 'paid'; // literal union

function label(student: Student | undefined, status: Status): string {
  // Optional chaining and nullish coalescing under strict null checks
  return `${student?.name ?? 'Unknown'} (${status})`;
}

function describe(value: string | number): string {
  if (typeof value === 'string') {
    return value.toUpperCase(); // narrowed to string
  }
  return value.toFixed(1); // narrowed to number
}

class Box<T> {
  items: T[] = [];
  add(item: T): void {
    this.items.push(item);
  }
}

const box = new Box<Student>();
box.add({ id: 1, name: 'Asha' });
// box.add({ id: 2 });  // compile error: name is missing
console.log(label(box.items[0], 'paid'), label(undefined, 'pending'));
console.log(describe('ok'), describe(3.14159));

TypeScript 5.8 strict mode. The code is type-checked, and the script runs in Node 24 twice with identical output.

Key points

  • TypeScript adds build-time types and compiles to JavaScript.
  • Daily features: interfaces, generics, unions and literal types, optional chaining, strict null checks.
  • `strict` and `strictTemplates` catch many errors early.
  • Types do not validate data at run time. Avoid `any`.

Common mistakes

  • Using `any` to silence errors.
  • Thinking `get<Student[]>` checks the server data.
  • Marking a field `private` and using it in the template.

Follow-ups

  • What is the difference between `interface` and `type`?
  • What does `strictNullChecks` change?
  • When would you use `unknown` instead of `any`?

Tips

  • Name five features and one run time limit.
  • Mention strict mode, as Angular enables it.
  • Prefer literal unions to enums, and say why.

Evaluation rubric

  • Explains the role of TypeScript in Angular.
  • Names practical features with examples.
  • Knows that types are build-time only.
157.angular-0157Easyfresher

Why does Angular code prefer creating new arrays and objects instead of changing them in place?

Angular compares references to find out what changed. If you push into an array or edit an object in place, the reference stays the same, so OnPush components, signals and pure pipes may not notice. Creating a new array or object (spread, map, filter) changes the reference and makes the change visible.

Full answer

In JavaScript an array or object variable holds a reference (an address), not the data itself. Many Angular features check "is this the same reference as before?" because it is fast: one comparison with ===, not a deep comparison of every item.

Where the reference check matters:

  1. Inputs of OnPush components. The child updates only when the input reference changes. students.push(newStudent) keeps the same array, so the child does not update. students = [...students, newStudent] gives a new reference.
  2. Signals. A signal notifies readers when the new value is not equal (by default, ===) to the old one. list.update(l => { l.push(x); return l; }) returns the same array, so nothing is notified. Use list.update(l => [...l, x]).
  3. Pure pipes. A pure pipe runs again only when its input reference changes.
  4. @for with track. Angular finds which items moved or were added by comparing the tracked keys.
  5. Store libraries (NgRx) rely on immutable updates for selectors to stay fast.

Immutable update patterns:

  • Add: [...list, item].
  • Remove: list.filter(x => x.id !== id).
  • Change one item: list.map(x => x.id === id ? { ...x, marks: 90 } : x).
  • Change an object: { ...student, marks: 90 }.
  • Sorting: [...list].sort(...) because sort changes the array in place. Newer methods toSorted, toSpliced and toReversed return copies.

Spread copies are shallow: only the first level is new. A nested object that you did not copy is still shared, which is usually fine, because it did not change.

Cost: copying large arrays on every key press is wasteful. For very large lists use pagination, virtual scroll or a library such as Immer. For small and medium lists the cost is negligible.

Mutation is not always a bug. In the default change detection mode, a mutation is seen on the next pass. Immutable updates matter when you use OnPush, signals and pure pipes, which modern Angular encourages.

typescript
export {};

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

const original: Student[] = [
  { id: 1, name: 'Asha', marks: 70 },
  { id: 2, name: 'Ravi', marks: 55 },
];

// Mutation: same reference, so a reference check sees "no change".
const mutated = original;
mutated.push({ id: 3, name: 'Meena', marks: 88 });
console.log('mutated same reference:', mutated === original, mutated.length);

// New reference for each change.
const added = [...original, { id: 4, name: 'Imran', marks: 61 }];
const removed = added.filter((s) => s.id !== 2);
const updated = removed.map((s) => (s.id === 1 ? { ...s, marks: 95 } : s));
console.log('added new reference:', added !== original);
console.log('updated item is new:', updated[0] !== original[0], 'other item shared:', updated[1] === original[2]);

const sorted = [...updated].sort((a, b) => b.marks - a.marks);
console.log(sorted.map((s) => `${s.name}:${s.marks}`).join(' '));
console.log('original order untouched:', original.map((s) => s.id).join(','));

TypeScript 5.8 with Node 24. The script was run twice with identical output. It shows that a mutated array keeps the same reference, and a spread copy does not.

Key points

  • Angular checks references with `===`, not deep content.
  • Mutating in place keeps the reference, so OnPush inputs, signals and pure pipes may miss the change.
  • Use spread, `map`, `filter` and `toSorted` to create new values.
  • Spread is shallow. Avoid copying very large lists on every event.

Common mistakes

  • Using `push` on an array that is an OnPush input or inside a signal.
  • Sorting a shared array in place.
  • Assuming spread makes a deep copy.

Follow-ups

  • Why does `signal.update` with a mutation not notify?
  • How do you change one item in a list immutably?
  • When can you still mutate safely?

Tips

  • Contrast `push` with spread in one line each.
  • Explain "reference" as an address.
  • Mention that default change detection hides the problem.

Evaluation rubric

  • Explains reference equality and why it is used.
  • Gives immutable patterns for add, remove and update.
  • Understands the cost and limits of spread.
158.angular-0158Easyfresher

What is the difference between routerLink, router.navigate and router.navigateByUrl, and how do you pass parameters with each?

routerLink is for links in templates. router.navigate takes a commands array and supports relative navigation and options. router.navigateByUrl takes one complete URL string and is always absolute. All of them return a promise (navigate and navigateByUrl) or render an anchor with a real href (routerLink).

Full answer

There are three ways to move to another page without a browser reload.

  1. routerLink (template). On an a element it renders a real href, so right click, open in new tab and search engines work. <a [routerLink]="['/courses', course.id]">Open</a> builds /courses/42. Add [queryParams]="{ level: 'easy' }" and fragment="reviews". Prefer it whenever the user clicks a link.
  2. router.navigate(commands, extras) (code). The commands are an array of path pieces: this.router.navigate(['/courses', id], { queryParams: { tab: 'info' } }). It supports relativeTo: this.route for relative paths, and options such as replaceUrl: true (replace the current history entry, useful after login), queryParamsHandling: 'merge' and state.
  3. router.navigateByUrl(url, extras) (code). It takes a full URL string or a UrlTree, such as '/courses/42?tab=info'. It is always absolute. Use it when you already have a complete URL, for example a returnUrl from a query parameter.

Differences in short:

  • Input: commands array versus one string versus a link in the template.
  • Relative navigation: navigate with relativeTo, and routerLink with relative paths such as ../. navigateByUrl has no relative mode.
  • Encoding: with navigate, path pieces are encoded for you, so a name with a slash is safe. With navigateByUrl you must encode the string yourself.

Common usage: after saving a form, await this.router.navigate(['/students']). The promise resolves to true when navigation finished, false when a guard blocked it, and rejects on an error.

Security note: do not pass an unchecked returnUrl to navigateByUrl. Check that it starts with / and not // to avoid redirecting users to another site. The router only handles in-app URLs, but a safe check keeps behaviour predictable.

typescript
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router, RouterLink, Routes } from '@angular/router';

@Component({ selector: 'app-list', template: `list` })
export class ListComponent {}

@Component({ selector: 'app-detail', template: `detail` })
export class DetailComponent {}

@Component({
  selector: 'app-nav',
  imports: [RouterLink],
  template: `<a [routerLink]="['/courses', 42]" [queryParams]="{ level: 'easy' }" fragment="reviews">Open course</a>`,
})
export class NavComponent {
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);

  openWithCommands(id: number): Promise<boolean> {
    return this.router.navigate(['/courses', id], { queryParams: { tab: 'info' } });
  }

  openWithUrl(): Promise<boolean> {
    return this.router.navigateByUrl('/courses/7?tab=notes');
  }

  openRelative(): Promise<boolean> {
    return this.router.navigate(['..'], { relativeTo: this.route });
  }
}

export const routes: Routes = [
  { path: 'courses', component: ListComponent },
  { path: 'courses/:id', component: DetailComponent, canActivate: [() => !inject(Router).url.includes('locked')] },
];

Angular 20.3. A Karma test checks the rendered href of the link, navigates with both methods, and checks the resulting URL, the query parameters and the boolean results. The relative navigation and the blocked navigation were not run.

Key points

  • `routerLink` is for template links and gives a real `href`.
  • `navigate` takes a commands array and supports `relativeTo` and options.
  • `navigateByUrl` takes a complete URL string and is absolute.
  • Both methods return a promise that tells you if navigation succeeded.

Common mistakes

  • Using a button with `(click)` and `navigate` when a plain `routerLink` anchor would do.
  • Passing a string with `navigate` and getting wrong URLs when it contains slashes.
  • Expecting `navigateByUrl` to be relative.

Follow-ups

  • How do you keep existing query params while changing one?
  • What does the promise from `navigate` resolve to?
  • How would you go back to the page the user wanted before login?

Tips

  • Start with when to use each, then differences.
  • Mention that `routerLink` renders a real link.
  • Show `replaceUrl` after login as a real example.

Evaluation rubric

  • Names all three and their inputs.
  • Explains relative navigation and encoding.
  • Knows the promise result and a security caution.
159.angular-0159Easyfresher

What do the form control state flags valid, invalid, touched, untouched, dirty, pristine and pending mean, and when do you use each?

valid and invalid tell if validation passes. touched means the user left the field, dirty means the user changed the value, and pending means an async validator is running. Show error messages when a field is invalid and touched or dirty, so users do not see errors before they have tried.

Full answer

Each FormControl, FormGroup and FormArray has flags that describe its state. They work in template-driven and reactive forms.

Validation state:

  • valid: all validators pass. invalid: at least one fails. The errors property holds the details, for example { required: true }.
  • pending: an async validator is still running. While pending, a control is neither valid nor invalid.
  • disabled: the control is excluded from validation and from form.value.

Interaction state:

  • touched: the user focused the field and then left it (a blur event happened). untouched is the opposite.
  • dirty: the user changed the value in the UI. pristine is the opposite.

Important detail: dirty is set by user input only. Calling control.setValue('x') in code does not make a control dirty (use markAsDirty() if you want that). touched can be set with markAsTouched(), and markAllAsTouched() on a group is the usual way to reveal all errors when the user presses submit on an incomplete form.

Using them for messages: an empty required field is invalid from the first moment, but showing "Name is required" before the user has typed anything feels rude. The common rule is @if (control.invalid && (control.touched || control.dirty)). For a submit button use form.invalid to disable it, or better, allow the click and show all errors.

Angular also adds CSS classes to the element: ng-valid, ng-invalid, ng-touched, ng-untouched, ng-dirty, ng-pristine, ng-pending. You can style input.ng-invalid.ng-touched { border-color: red; }. Group flags combine their children: a group is invalid if any child is invalid, dirty if any child is dirty.

Resetting: form.reset() sets the value to its initial state and marks controls pristine and untouched. For accessibility, connect the message to the field with aria-describedby and use role="alert" for errors that appear after submit.

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

export function flagsDemo(): string[] {
  const name = new FormControl('', { nonNullable: true, validators: [Validators.required] });
  const snap = (step: string) =>
    `${step}: valid=${name.valid} touched=${name.touched} dirty=${name.dirty}`;

  const out: string[] = [snap('start')];

  name.markAsTouched(); // what a blur event does
  out.push(snap('after blur'));

  name.setValue('Asha'); // code change
  out.push(snap('after setValue'));

  name.markAsDirty(); // what typing in the field does
  out.push(snap('after typing'));

  name.reset();
  out.push(snap('after reset'));
  return out;
}

Angular 20.3. A Karma test records the flags of a control before typing, after a blur, after user input, after setValue, and after reset.

Key points

  • `valid`, `invalid`, `pending` describe validation. `touched` means blurred. `dirty` means the user changed the value.
  • `setValue` in code does not make a control dirty.
  • Show errors when invalid and touched or dirty. Use `markAllAsTouched()` on submit.
  • Angular adds matching `ng-*` CSS classes. Group flags combine child flags.

Common mistakes

  • Showing errors on a pristine, untouched empty field.
  • Expecting `setValue` to mark the control dirty.
  • Forgetting that `pending` is neither valid nor invalid.

Follow-ups

  • How do you show all errors when the user presses submit?
  • What happens to the flags after `form.reset()`?
  • Why can a group be dirty while one child is pristine?

Tips

  • Contrast touched and dirty with one sentence each.
  • Mention `markAllAsTouched`.
  • Mention accessibility of the error message.

Evaluation rubric

  • Defines each flag correctly.
  • Knows how flags change and how to set them in code.
  • Applies them to a good error message rule.
160.angular-0160Easyfresher

Angular shows "is not a known element" or "Can't bind to X since it isn't a known property of Y". What causes these errors and how do you fix them?

In a standalone component, every component, directive or pipe used in the template must be listed in that component's imports array. These errors mean the compiler found a tag or binding that no imported item defines. Fix by importing the right standalone class (or FormsModule, RouterLink and so on), or by correcting a typo.

Full answer

These are the most common errors for beginners. They are template errors that the compiler reports (NG8001 for an unknown element, NG8002 for an unknown property), and in a test or JIT run you may see them in the console.

Typical messages:

  • NG8001: 'app-student-card' is not a known element. Angular found a tag that is not a standard HTML tag and not a component it knows.
  • NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'. Angular found a binding such as [ngModel] or [routerLink] and no imported directive provides that input.
  • NG8004: No pipe found with name 'currency'. A pipe is used but not imported.

Why it happens: in standalone components (the default now) the template can only use what the component lists in imports. Nothing is global, unlike old NgModules where one module declared many things.

Fix by checking, in order:

  1. Is the item imported? Add the class: imports: [StudentCardComponent], imports: [FormsModule] for ngModel, imports: [RouterLink], imports: [ReactiveFormsModule] for formGroup, and CurrencyPipe for the currency pipe. The built-in control flow (@if, @for) needs no import, but NgClass and NgStyle must be imported like any other directive.
  2. Is the selector spelt correctly? app-student-card in the template must match the selector in the component. A typo gives the same error.
  3. Is the imported class standalone? A component that is declared in an NgModule must be imported through that module.
  4. Is the input real? [disable] instead of [disabled] is "not a known property". Check the name in the component's input().
  5. Did you forget the [] or use a custom element? For Web Components, add CUSTOM_ELEMENTS_SCHEMA to schemas, but do not use it to silence real mistakes, because it hides typos.

In tests: declare or import the component under test, and its dependencies, in TestBed.

Learn the habit: when the editor shows the error, read the name in quotes, and ask "which class provides this, and is it in my imports?"

typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';

@Component({
  selector: 'app-fee-card',
  template: `<p>Fee card</p>`,
})
export class FeeCardComponent {}

// Broken: nothing is imported. ngc reports:
//   NG8001: 'app-fee-card' is not a known element
//   NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'
//   NG8004: No pipe found with name 'currency'
//   @Component({
//     selector: 'app-fee-form',
//     template: `<app-fee-card /> <input [(ngModel)]="fee" /> {{ fee | currency }}`,
//   })
//
// Fixed: import each item that the template uses.
@Component({
  selector: 'app-fee-form',
  imports: [FeeCardComponent, FormsModule, CurrencyPipe],
  template: `<app-fee-card /> <input [(ngModel)]="fee" name="fee" /> {{ fee | currency }}`,
})
export class FeeFormComponent {
  fee = 1500;
}

Angular 20.3. The compiler messages in the code comment were produced by running `ngc` on the broken version of this component, and the fixed version compiles cleanly.

Key points

  • In standalone components, only items listed in `imports` can be used in the template.
  • NG8001 is an unknown element, NG8002 is an unknown property, NG8004 is an unknown pipe.
  • Fix by importing the class, correcting a typo, or importing the right module.
  • Use `CUSTOM_ELEMENTS_SCHEMA` only for real Web Components.

Common mistakes

  • Silencing errors with `CUSTOM_ELEMENTS_SCHEMA` or `NO_ERRORS_SCHEMA`.
  • Importing a module into the parent and expecting the child to see it.
  • Spelling the selector or input name wrongly.

Follow-ups

  • Why does a child component not inherit the parent's imports?
  • What does `NO_ERRORS_SCHEMA` hide?
  • How do you fix this error in a unit test?

Tips

  • Give the checklist in order.
  • Say that imports are per component.
  • Warn against schemas as a shortcut.

Evaluation rubric

  • Explains the cause in standalone terms.
  • Gives a clear fix order.
  • Avoids bad shortcuts.