▚ The Software Engineer's Field Manual
Chapter E14 · Standalone framework track

Angular Primer — From Zero to Working Code

"Angular is not a library you sprinkle on a page. It is an opinionated application framework — and once you see the four ideas it is built from, the opinions stop feeling like rules and start feeling like relief."

~14 hours For: anyone new to Angular — no prior Angular assumed Angular 22 · signals · zoneless · standalone components

01 · The hookThe Framework That Punishes Copy-Paste and Rewards Understanding

Angular is a complete framework for building web applications: it gives you components, routing, forms, HTTP, testing and a build system in one box. This chapter teaches it from your first command, assuming you have never written a line of it.

Field report · Frontend hiring, a mid-size product company

"I ask one question early and it decides most of the interview: your list component shows stale data after a save — walk me through why.

One kind of candidate starts naming things. Change detection. Zone.js. Maybe ChangeDetectorRef. They have read the words. When I ask which of those would you actually check first, and what would you look at, the answer dissolves.

The other kind asks me a question back: is the list bound to a signal, or to a plain array the service mutates? That candidate has been bitten. They know Angular only re-renders what it has been told changed, and they know the two ways of telling it.

Both candidates have 'Angular' on the CV for the same number of years. The second one learned what the framework is doing. The first learned which incantations made the error go away."

— Priya N., frontend lead, product company, Bengaluru

This chapter is built to make you the second candidate. It teaches Angular from zero. No prior Angular is assumed, and no prior framework experience either.

What you do need is working JavaScript: variables, functions, arrays, objects, and roughly what a promise is. If any of that is shaky, read Chapter E11 · JavaScript Primer first and come back. Everything else — TypeScript, decorators, dependency injection, reactivity — is introduced here from scratch.

What Angular actually is, before any code

A web page is HTML. HTML is static text: it describes what is on the screen at the moment it loads, and it has no idea what to do when a number changes.

Every frontend framework exists to solve one problem: keeping the screen in agreement with your data. You change a value in memory; the screen must show the new value. That is the entire job.

You could do it by hand. Find the element, set its text, remember to do it again next time. That is what plain JavaScript gives you, and it works until your app has forty screens and four hundred places where data can change.

Angular takes a different deal. You write a template — HTML with holes in it — and you write a class holding the data. Angular keeps them in agreement for you, forever, and you never touch the page directly again.

That is the trade at the centre of the framework. You give up direct control of the page. You get back the guarantee that the page is never wrong.

The four ideas the whole framework is made of

Angular has a reputation for being large. It is large, but it is not complicated in a deep way. Almost everything in it is one of four ideas, and this chapter teaches them in this order.

Table 1 — The four ideas, and the question each one answers
IdeaThe question it answersTaught in
Component"What is one piece of my screen, and what data does it need?"Section 04
Signal"How does the screen find out that a value changed?"Section 05
Dependency injection"How does a component get hold of shared things — a data service, a logger, the router?"Section 07
Router"Which components are on screen for this URL?"Section 09

Forms, HTTP, testing and the build system are all built on top of those four. When a piece of Angular confuses you later, the useful move is to ask which of the four it belongs to.

You already know this

Three of the four ideas already exist in your life, under other names.

A component is a form template with fields. "Invoice header" is a component: a fixed layout with blanks for the customer name and the date. Print it a hundred times with different blanks filled in and you have a hundred invoices from one design.

A signal is a magazine subscription. You do not phone the publisher every morning to ask whether a new issue exists. You subscribe once, and the issue arrives when it is printed. Angular subscribes your screen to your data, once.

Dependency injection is the office supply cupboard. You do not manufacture your own stapler; you ask for one and the office hands you the shared one. Components ask for services the same way, and the framework hands them the shared instance.

Everything in this chapter is those three ideas plus a URL-to-screen lookup table, worked out carefully.

Why Angular and not React, in one honest paragraph

You will be asked this, so here is the truthful version. React is a library for rendering views; you assemble the rest of your application from community packages, and you make those choices yourself.

Angular is a framework that has already made those choices: routing, forms, HTTP, testing and the build tool ship in the box and are versioned together.

That is worse when you want to do something unusual, and better when you have forty engineers, a five-year product, and a strong preference that every screen in the codebase looks the same.

Which is why Angular concentrates in enterprises, banks, telecoms, healthcare, internal tooling and large product teams — and why React concentrates in startups, agencies, and anything where the page needs to be unusual. Neither is a mistake. Chapter E16 compares them properly, side by side.

What version this chapter teaches, and why that matters more than usual

Angular ships a new major version every six months. As of September 2026 the current release is Angular 22, which arrived in June 2026.

This matters because Angular changed more between 2023 and 2026 than in the six years before it. Tutorials written for Angular 14 teach a genuinely different framework.

Three changes are the big ones, and this chapter teaches only the current way.

Table 2 — What changed, and what an old tutorial will teach you by mistake
AreaThe old way (pre-2024)The current way (this chapter)
Wiring components together NgModule — a separate declarations file listing every component Standalone components — each component declares its own imports. NgModule is optional and mostly gone
Reacting to changes Zone.js — a library that patched every browser API to guess when something might have changed Signals and zoneless change detection — values tell the framework directly when they change
Template conditionals and loops *ngIf, *ngFor, *ngSwitch structural directives Built-in control flow: @if, @for, @switch — real syntax, not directives

You will still meet all three old forms in real codebases, because most production Angular applications are somewhere mid-migration. So this chapter teaches the current way first, then shows you the old form and names it, so you can read a five-year-old file without confusion.

Every code block on this page runs on Angular 22 as written.

Quick reference — What Angular is

The job of a frontend framework
Keep the screen in agreement with your data, without you touching the page by hand.
Component
One piece of the screen: a template with holes, plus a class holding the data that fills them.
Signal
A value that tells the framework when it changes, so only the screens using it get re-rendered.
Dependency injection
Ask the framework for a shared object instead of constructing your own.
Framework vs library
Angular ships routing, forms, HTTP, testing and the build tool together and versions them as one. React ships rendering and you choose the rest.
Version as of September 2026
Angular 22, released June 2026. Standalone components, signals and built-in control flow are the defaults; NgModule, Zone.js and *ngIf are the legacy forms you will still read.

02 · Getting set upOne Command, One App, Every Generated File Explained

You need Node.js and one command-line tool. The tool generates a working application, and this section walks through every file it created so nothing on your disk is a mystery.

Angular is not something you drop into a page with a script tag. It is compiled: your TypeScript and templates are turned into optimised JavaScript before a browser ever sees them.

That compilation needs a toolchain, and the toolchain runs on Node.js. So there are exactly two installs.

Step one: install Node.js

Node.js is a program that runs JavaScript outside a browser. Angular's build tools are written in JavaScript, so Node is what runs them. You will not write Node code in this chapter — it is here purely to power the build.

Get the LTS build from nodejs.org. LTS stands for long-term support, the version kept stable for years rather than the newest one. Angular 22 needs Node 20.19 or newer.

Check both installs worked:

terminal — verify the toolchainruns offline
node --version     # v22.x.x or newer  -- the JavaScript runtime
npm --version      # 10.x or newer     -- the package installer, ships with Node

npm is the node package manager. It downloads libraries from a public registry into a folder called node_modules. It comes with Node; you do not install it separately.

Step two: install the Angular CLI

The Angular CLI (command-line interface) is the tool that generates projects, generates files inside them, runs the development server, runs tests, and produces the production build. It is the single door to everything.

terminal — install the CLI globallyruns offline
# -g means "global": install it once for your whole machine, not per project
npm install -g @angular/cli

ng version         # prints the CLI version and the Angular packages it will use

The command is ng, short for Angular. If your shell says ng: command not found after a successful install, your system's PATH does not include npm's global folder — run npm config get prefix, and add the bin folder inside it to PATH.

Step three: generate and run your first app

terminal — create and runruns offline
ng new task-board          # answer the prompts: CSS, and SSR = No for now
cd task-board
ng serve                   # starts a development server on http://localhost:4200

ng new asks two or three questions. Choose plain CSS for styling — the alternatives (Sass, Less) are conveniences you do not need yet. Answer No to server-side rendering; it is a real feature, covered in Chapter E15, and it adds files that would only distract you now.

Open http://localhost:4200 and you have a running Angular application. Leave ng serve running in that terminal for the rest of this chapter. It watches your files and reloads the browser on every save, usually in under a second.

Reading the folder it made

A generated Angular app has about a dozen files that matter and a few thousand in node_modules that do not. Here is every one that matters.

task-board/ — the files you will actually openruns offline
task-board/
├── src/
│   ├── main.ts            <- the very first line of your code that runs
│   ├── index.html         <- the single real HTML page the browser loads
│   ├── styles.css         <- styles that apply to the whole application
│   └── app/
│       ├── app.ts         <- the root component's class
│       ├── app.html       <- the root component's template
│       ├── app.css        <- styles for that component only
│       ├── app.config.ts  <- application-wide setup (router, HTTP, and so on)
│       └── app.routes.ts  <- the URL-to-component table
├── angular.json           <- build configuration; you rarely edit it by hand
├── package.json           <- your dependencies and npm scripts
├── tsconfig.json          <- TypeScript compiler settings
└── node_modules/          <- downloaded libraries. Never edit, never commit

Three of those deserve a proper walk-through, because they explain how an Angular app actually starts.

index.html — the only page there is

src/index.htmlruns offline
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TaskBoard</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Read the file. There is one unusual tag: <app-root>. That is not an HTML element the browser knows. It is the name of your root component, and Angular replaces its contents with your entire application at startup.

This is why Angular apps are called single-page applications. The browser loads exactly one HTML file, ever. Every "page" after that is Angular swapping components in and out inside that one tag.

<base href="/"> tells the router what the root of your URLs is. Delete it and routing breaks in ways that are hard to diagnose, so leave it alone.

main.ts — the first line of your code that runs

Step-by-step: what main.ts does, in plain English
  1. Import bootstrapApplication — the function that starts an Angular app. "Bootstrap" here means "start up from nothing".
  2. Import appConfig, the object listing application-wide services, from app.config.ts.
  3. Import App, the root component class, from app.ts.
  4. Call bootstrapApplication(App, appConfig). Angular finds the <app-root> tag in the page, creates one instance of the App component, renders its template into that tag, and starts watching for changes.
  5. Attach .catch(...) so that if startup fails, the error is printed to the console instead of vanishing. bootstrapApplication returns a promise, and an unhandled rejected promise is silent.
src/main.tsruns offline
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';

bootstrapApplication(App, appConfig)
  .catch((err) => console.error(err));

Five lines. That is the whole startup story, and it is worth holding on to: find the tag, build the root component, render it, watch it.

app.config.ts — where application-wide things are registered

src/app/app.config.tsruns offline
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
  ],
};

A provider is a registration: "when any part of this application asks for X, here is how to build it." provideRouter(routes) registers the router and hands it your URL table.

Later you will add provideHttpClient() here to enable server calls. This one file is where every application-wide capability gets switched on, which makes it the first file to read in an unfamiliar Angular codebase.

A note on zoneless, if you are reading older tutorials

Older app.config.ts files contain provideZoneChangeDetection(...), and older ones still contain nothing about change detection at all. Both mean the app uses Zone.js, a library that patched every browser API — every setTimeout, every click handler, every network response — so Angular could guess when to re-check the screen.

Since Angular 21 the default is zoneless: no patching, and the framework re-renders only when a signal it is watching actually changes. New apps get this automatically and you do not configure anything.

You do not need to understand zones to finish this chapter. You do need to know the word, because it is the single most common senior Angular interview topic, and it gets a full treatment in Chapter E15.

Quick reference — Setup

Node.js
Runs JavaScript outside the browser. Angular's build tools need it. Use the LTS build, 20.19 or newer for Angular 22.
ng new / ng serve / ng build
Generate a project, run the watching development server on port 4200, produce the optimised production bundle in dist/.
<app-root>
The placeholder tag in index.html that Angular fills with your whole application.
main.ts
Calls bootstrapApplication(RootComponent, config). That is the entire startup path.
app.config.ts
The providers array where application-wide features are switched on — router, HTTP client, and anything else shared by the whole app.
Single-page application
One HTML file is ever loaded. Navigation swaps components inside it rather than fetching new pages.

03 · The languageThe TypeScript You Need Before Angular Makes Sense

TypeScript is JavaScript with labels on the values, checked before your code runs. Angular is written in it and expects it, so this section teaches the six pieces of TypeScript the rest of the chapter uses — and nothing more.

You cannot skip this. Angular's error messages are TypeScript error messages, and a person who does not read TypeScript reads them as noise.

The good news is that TypeScript is not a new language. It is JavaScript with one addition: you may write down what kind of value a variable holds, and a compiler checks that you were telling the truth.

What a type actually buys you

Here is the whole pitch in six lines. The first block is JavaScript, and it is wrong in a way nothing notices until a user hits it.

plain JavaScript — the bug shipsruns offline
function total(price, quantity) {
  return price * quantity;
}

total(19.99, "3");      // 59.97 -- worked by luck, JS coerced "3" to 3
total(19.99, "three");  // NaN   -- shipped, crashed a report at 2am
TypeScript — the bug never compilesruns offline
function total(price: number, quantity: number): number {
  return price * quantity;
}

total(19.99, "three");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.

Read the difference. The annotations : number are the only new syntax. They say what each parameter holds and what the function returns.

The compiler now refuses the bad call. Nothing about the running program changed — TypeScript's types are erased before the browser sees the code. The check happens at your desk, not at the user's.

This is the mental model to keep: TypeScript is a spell-checker for values, and it runs before your program does.

The six pieces you need

TypeScript is a large language, and you need a small corner of it. These six pieces cover every line of TypeScript in the rest of this chapter.

One — annotations on variables, parameters and returns

annotations.tsruns offline
let title: string = 'Task Board';    // holds text
let count: number = 0;                // holds a number -- there is no int/float split
let done: boolean = false;            // true or false
let tags: string[] = ['work', 'home'];// an array where every item is text

// Most of the time you can leave the annotation out. TypeScript infers it:
let inferredTitle = 'Task Board';     // inferred as string, identical to above

// Functions: annotate the parameters, let the return type be inferred.
function shout(message: string) {
  return message.toUpperCase();       // return type inferred as string
}

Annotate parameters; let everything else be inferred. That is the working rule. Writing let count: number = 0 is not wrong, but it is noise — the compiler already knew.

Two — interfaces, for the shape of an object

An interface names the shape of an object: which properties it has, and what type each holds. This is the single most-used TypeScript feature in Angular code, because every screen displays objects that came from a server.

task.model.tsruns offline
export interface Task {
  id: number;
  title: string;
  done: boolean;
  dueDate?: string;        // the ? means optional -- may be absent or undefined
  readonly createdAt: string; // readonly: can be read, cannot be reassigned
}

const t: Task = { id: 1, title: 'Write the primer', done: false, createdAt: '2026-09-07' };

t.done = true;             // fine
t.createdAt = 'tomorrow';  // Error: Cannot assign to 'createdAt', it is read-only.
const x: Task = { id: 2, title: 'Oops' };
// Error: Property 'done' is missing in type '{ id: number; title: string; }'.

Read the two errors. The first catches a mutation you did not intend. The second catches an object you forgot to finish building — which in real code is usually a server response that changed shape without telling you.

Put interfaces in their own small files, one per concept, and export them. Angular projects conventionally name them *.model.ts.

Three — union types and narrowing

A union type says a value is one of several types. You write it with a vertical bar. This is how TypeScript models "loading, or loaded, or failed" — the state every real screen is in.

unions.tsruns offline
type Status = 'idle' | 'loading' | 'error' | 'ready';  // a union of exact strings

let status: Status = 'loading';
status = 'finished';   // Error: Type '"finished"' is not assignable to type 'Status'.

function describe(value: string | number) {
  // Inside this branch, TypeScript KNOWS value is a string. This is "narrowing".
  if (typeof value === 'string') {
    return value.trim();      // .trim() exists on string
  }
  return value.toFixed(2);    // here it must be number, so .toFixed() is allowed
}

Narrowing is the compiler following your if statement. After typeof value === 'string', it stops treating the value as "string or number" and treats it as a string. You get correct autocompletion inside each branch for free.

The union of exact strings — 'idle' | 'loading' | ... — is worth noticing. It gives you an enumeration with no enum keyword, and a typo becomes a compile error.

Four — null, undefined, and the two operators for them

Angular projects are generated with strict mode on. In strict mode a string can never be null: if it might be, you must say so.

nullability.tsruns offline
let name: string = null;          // Error in strict mode.
let maybeName: string | null = null;  // Fine -- you declared the possibility.

console.log(maybeName.length);   // Error: 'maybeName' is possibly 'null'.

// Operator 1 -- optional chaining. Stop and give undefined if the left side is null.
console.log(maybeName?.length);  // undefined, no crash

// Operator 2 -- nullish coalescing. Use the right side if the left is null/undefined.
const display = maybeName ?? 'Anonymous';   // 'Anonymous'

// Note the difference from ||, which also replaces 0 and '' -- usually a bug:
const count = 0;
console.log(count || 10);   // 10  <- wrong, 0 is a real value
console.log(count ?? 10);   // 0   <- right

Read the last two lines carefully. That distinction — || replaces every falsy value, ?? replaces only null and undefined — is a genuine production bug source and a routine interview question. A quantity of zero is a real quantity.

Five — generics, read as "a container of what?"

A generic is a type with a blank in it. Array on its own is not a useful description; Array<Task> is. The angle brackets fill the blank.

generics.tsruns offline
const tasks: Array<Task> = [];      // an array whose items are Tasks
const names: string[] = [];         // shorthand for Array<string>, same thing

// A promise for a Task, not a promise for "something"
function loadTask(id: number): Promise<Task> {
  return fetch(`/api/tasks/${id}`).then(r => r.json());
}

// Writing your own: T is a placeholder filled in at the call site.
function firstOrNull<T>(items: T[]): T | null {
  return items.length > 0 ? items[0] : null;
}

const t = firstOrNull(tasks);       // t is Task | null -- inferred, no annotation needed
const s = firstOrNull(names);       // s is string | null

You will read far more generics than you write. When you see Signal<Task[]> or HttpClient.get<Task>() later in this chapter, read it as "a signal holding an array of tasks" and "a GET that produces a Task". That is all the angle brackets ever mean.

Six — classes and decorators

Every Angular component is a class with a decorator on top, so these two go together.

A class is a blueprint for objects: it holds data (properties) and behaviour (methods). If you know Java classes, TypeScript classes are the same idea with lighter syntax.

classes.tsruns offline
class Counter {
  private value = 0;              // private: reachable only inside this class

  increment(): void {             // a method. void = returns nothing
    this.value++;
  }

  get current(): number {         // a getter: read like a property, runs like a method
    return this.value;
  }
}

const c = new Counter();
c.increment();
console.log(c.current);           // 1  -- note: no parentheses, it is a getter
c.value = 99;                     // Error: 'value' is private.

A decorator is the @Something line written directly above a class. It is a function that attaches information to the class — it does not change what the class does by itself.

Think of it as a label on a box. @Component({...}) means "this class is a component, and here are its settings". Angular reads those labels at build time and generates the code that makes the class behave like a component.

decorator-shape.ts — the shape you will see everywhereruns offline
import { Component } from '@angular/core';

@Component({                     // <- the decorator, with its configuration object
  selector: 'app-hello',
  template: `<p>Hello</p>`,
})
export class Hello {}            // <- an ordinary class. The decorator gave it meaning.

That is the six pieces. Annotations, interfaces, unions, nullability, generics, classes-with-decorators. Every TypeScript line in the rest of this chapter is one of them.

🧠 Brain power

Before you read on: interface Task has dueDate?: string. What exact type does TypeScript give task.dueDate, and why can you not call task.dueDate.slice(0, 4) on it directly?

Think first, then open

The type is string | undefined. The ? did not merely mark the property optional when constructing the object — it widened the property's type to include undefined everywhere it is read.

So .slice() is refused, because undefined has no .slice. You fix it with narrowing (if (task.dueDate) { ... }), with optional chaining (task.dueDate?.slice(0, 4)), or with a default ((task.dueDate ?? '').slice(0, 4)).

This is the exact shape of most Angular template bugs: server data whose fields are optional, read as though they never are.

Quick reference — TypeScript for Angular

What TypeScript is
JavaScript plus type annotations, checked at compile time and erased before the browser runs anything. No runtime cost, no runtime protection.
interface
Names the shape of an object. ? makes a property optional and adds undefined to its type. readonly blocks reassignment.
Union type A | B
The value is one of these. A union of exact strings gives you an enumeration where typos fail to compile.
Narrowing
The compiler following your if: inside if (typeof v === 'string'), v is a string.
?. vs ?? vs ||
?. stops at null and yields undefined. ?? substitutes only for null/undefined. || also substitutes for 0 and '', which is usually the bug.
Generic X<T>
A container type with the contents named. Read Signal<Task[]> as "signal holding an array of tasks".
Decorator @Component({...})
A label above a class carrying configuration. Angular reads it at build time; it does nothing on its own.

04 · The first ideaComponents & Templates — HTML With Holes In It

A component is one piece of your screen: a class holding data, a template describing the markup, and a name you can use as an HTML tag. Your whole application is a tree of them.

Start with the shape. Every Angular component is exactly four things, and three of them are optional in the sense that they have sensible defaults.

Table 3 — The four parts of every component
PartWhat it isWhere it lives
SelectorThe tag name you write to place this component on a pageselector: in the decorator
TemplateThe HTML, with holes where data goestemplateUrl: a separate file, or template: inline
ClassThe data and the methods that change itThe exported class under the decorator
StylesCSS that applies to this component and nothing elsestyleUrl: or styles:

Generating one, and reading every line

Never hand-write a component file. The CLI generates it correctly and puts it in the right place.

terminal — generate a componentruns offline
# "g c" is short for "generate component". Both forms work.
ng generate component task-card

# CREATE src/app/task-card/task-card.ts
# CREATE src/app/task-card/task-card.html
# CREATE src/app/task-card/task-card.css
# CREATE src/app/task-card/task-card.spec.ts     <- the test file, free of charge
Step-by-step: what task-card.ts does, in plain English
  1. Import Component — the decorator function — from Angular's core package.
  2. Import the Task interface, so the compiler knows the shape of the data this component displays.
  3. Apply @Component({...}) to the class below, handing it a configuration object.
  4. Set selector: 'app-task-card'. From now on, writing <app-task-card> in any template that imports this class places one of these on the screen.
  5. Set imports: []. This is the standalone component's own dependency list: every other component, directive or pipe its template uses must be named here. An empty list means the template uses only built-in syntax.
  6. Point templateUrl and styleUrl at the sibling files, keeping markup and styles out of the TypeScript.
  7. Export the class. The class body holds the data the template will read and the methods the template will call.
src/app/task-card/task-card.tsruns offline
import { Component } from '@angular/core';

@Component({
  selector: 'app-task-card',      // usable as <app-task-card></app-task-card>
  imports: [],                    // this component's own dependencies
  templateUrl: './task-card.html',
  styleUrl: './task-card.css',
})
export class TaskCard {
  title = 'Write the Angular primer';
  done = false;

  toggle(): void {
    this.done = !this.done;
  }
}

The word standalone describes that imports array. Before Angular 14, components could not declare their own dependencies — a separate NgModule file had to list every component in a chunk of the app, and forgetting to add yours produced the most-searched error message in Angular's history.

Since Angular 19, standalone is the default and you do not write the word. If you open a file with standalone: true in it, that is a project that has migrated but not yet cleaned up. If you open one with an NgModule, that is a project that has not migrated.

The four bindings — how data gets into the HTML

A template is HTML plus four pieces of Angular syntax. Once you can recognise the punctuation, you can read any Angular template ever written.

Table 4 — The four bindings, and which direction data flows
SyntaxNameDirectionUse it when
{{ value }}InterpolationClass → screenYou want to display text
[property]="value"Property bindingClass → screenYou want to set an element's property — disabled, src, value
(event)="handler()"Event bindingScreen → classYou want to run a method on click, input, submit
[(ngModel)]="value"Two-way bindingBothA form input whose value must stay in step with a field

The punctuation is a deliberate mnemonic. Square brackets look like a box being filled from your class. Parentheses look like a mouth shouting an event back. Two-way binding uses both, and the community nickname for [( )] is "banana in a box".

src/app/task-card/task-card.html — all four bindingsruns offline
<!-- 1. Interpolation: put the value of this.title here as text -->
<h3>{{ title }}</h3>

<!-- 2. Property binding: set the button's disabled PROPERTY from this.done -->
<button [disabled]="done" (click)="toggle()">Mark done</button>

<!-- 3. Event binding: (click) runs the method. $event is the DOM event object. -->
<button (click)="toggle()">Toggle</button>

<!-- Class and style bindings are property bindings with a suffix -->
<p [class.completed]="done">Strikethrough when done</p>
<p [style.opacity]="done ? 0.5 : 1">Faded when done</p>

<!-- Interpolation runs an expression, not a statement. This is allowed: -->
<span>{{ title.length }} characters, {{ done ? 'done' : 'open' }}</span>

Read the third line. [disabled]="done" sets the DOM property called disabled to the boolean in this.done. Writing disabled="{{ done }}" instead would set the HTML attribute to the string "false" — and in HTML, the mere presence of the disabled attribute disables the button, whatever its value. The button would be permanently dead.

That distinction — attributes are the initial HTML text, properties are the live DOM state — is the single most common Angular beginner bug and a guaranteed interview question. Bind to properties.

What you may and may not write inside a template

A template expression is not arbitrary JavaScript. Angular restricts it on purpose.

You can read properties, call component methods, use arithmetic and comparison, use the ternary ? :, and use ?. and ??.

You cannot use new, assignment with = outside an event binding, ++, bitwise operators, or reach global objects like window and console.

The reason is that a template expression is re-evaluated whenever Angular re-renders. Anything with a side effect would fire an unpredictable number of times, and anything slow would be slow that many times.

Which gives the rule that keeps templates fast: never call a method that does real work from a template. Compute it once in the class, expose the result, and bind to that. Section 05 shows the tool for exactly this.

Control flow: @if, @for, @switch

Templates need branches and loops. Since Angular 17 these are real syntax, written with an @ sign, and they need no imports at all.

control-flow.htmlruns offline
@if (tasks.length === 0) {
  <p class="empty">Nothing to do. Enjoy it.</p>
} @else if (loading) {
  <p>Loading…</p>
} @else {
  <ul>
    @for (task of tasks; track task.id) {
      <li>{{ task.title }}</li>
    } @empty {
      <li>No tasks matched the filter.</li>
    }
  </ul>
}

@switch (status) {
  @case ('loading') { <app-spinner /> }
  @case ('error')   { <p class="error">Could not load.</p> }
  @default          { <app-task-list /> }
}

The track clause is not optional and not decoration. It tells Angular how to recognise the same item across two renders — here, by task.id.

Without a stable identity, Angular cannot tell "the list was reordered" from "every row is new", so it destroys and rebuilds every row. You lose focus in inputs, lose scroll position, lose animation state, and re-render a hundred rows to move one.

Track by a stable unique identifier from your data. Track by the loop index only for lists that never reorder and whose items have no other identity.

Data changes: [A, B, C] becomes [C, A, B] track task.id A B C move 3 ops C A B same DOM nodes reused focus and scroll survive no stable track A B C destroy + recreate C' A' B' all new DOM nodes focus lost, inputs cleared
Figure 1 — Reordering a three-item list. With track task.id Angular recognises the same rows and moves them. Without a stable identity it throws all three away and builds three new ones, taking focus and scroll position with them.

@let — naming a value inside a template

Sometimes a template needs the same computed value twice, and repeating the expression is both slower and uglier. @let declares a local template variable.

let.htmlruns offline
@let overdue = task.dueDate && task.dueDate < today;

<li [class.late]="overdue">
  {{ task.title }}
  @if (overdue) { <span class="badge">overdue</span> }
</li>

@let is read-only: you declare it and you use it, you never reassign it. It is scoped to the block it was declared in and everything nested inside.

The old syntax, so you can read old code

You will open files written before Angular 17. Here is the same logic in both forms, so the old one never puzzles you.

Table 5 — Old structural directives and their modern equivalents
Old (needs CommonModule imported)Modern (built in, no import)
<p *ngIf="ready">Hi</p>@if (ready) { <p>Hi</p> }
<p *ngIf="ready; else load"> plus <ng-template #load>@if (ready) { … } @else { … }
<li *ngFor="let t of tasks; trackBy: byId">@for (t of tasks; track t.id) { <li>…</li> }
[ngSwitch] / *ngSwitchCase@switch / @case

The asterisk in *ngIf was shorthand for wrapping the element in an invisible <ng-template>. That is why the old else-branch needed a separate named template and the new one does not.

You never need to write the old form. The CLI can convert a whole project for you with ng generate @angular/core:control-flow.

Styles are scoped to the component, by default

CSS you write in task-card.css applies to task-card.html and nowhere else — even if the selector is as broad as p { color: red; }.

Angular does this by adding a generated attribute to every element the component rendered, and rewriting your selectors to require that attribute. You can see it in the browser's element inspector as something like _ngcontent-ng-c123456.

This is view encapsulation, and it is the reason large Angular codebases do not descend into CSS conflicts. Global styles still belong in src/styles.css, which is deliberately not scoped.

Failure mode — styling a child component from a parent

Encapsulation means a parent's CSS cannot reach inside a child component. Writing .card h3 { color: red; } in the parent silently does nothing, which is a confusing hour the first time.

The escape hatch is ::ng-deep, and it works — but it leaks globally unless you scope it to something the component owns, and it is on a long, slow path to deprecation.

The right answer nearly always is to let the child expose the choice: give it an input for the variant, or style it with CSS custom properties, which pass through encapsulation because they are inherited values rather than selectors.

Quick reference — Components and templates

The four parts
Selector (the tag), template (the HTML), class (the data), styles (scoped CSS).
Standalone
The component declares its own imports. Default since Angular 19; the NgModule alternative is legacy.
{{ }} / [x] / (y) / [(z)]
Text out, property in, event out, both. Bind to DOM properties, not HTML attributes — [disabled]="false" works, disabled="{{false}}" disables permanently.
@if / @for / @switch
Built-in control flow since Angular 17. No imports needed. @for also has @empty.
track
Required in @for. Gives each item a stable identity so Angular moves DOM nodes instead of rebuilding them. Track by a unique id, not the index, whenever the list can reorder.
@let
A read-only local name for a value inside a template, scoped to its block.
Template expression limits
No new, no assignment, no window. Re-evaluated on every render, so never call expensive methods from a template.
View encapsulation
Component CSS is rewritten to match only that component's elements. Parents cannot style into children; expose an input or a CSS custom property instead.

05 · The second ideaSignals — State the Framework Can Actually See

A signal is a value in a box that tells Angular whenever it changes. Because Angular knows exactly which parts of the screen read which box, it can re-render only those parts and nothing else.

Go back to the one job a framework has: keep the screen in agreement with the data. There is a hard sub-problem hiding inside it, and signals exist to solve that sub-problem.

The sub-problem is: how does the framework find out that something changed?

A plain field cannot help. When you write this.count = this.count + 1, JavaScript assigns a number and tells nobody. There is no hook, no event, no notification. The framework has no way to know it happened.

How Angular used to guess, and why it stopped

The old answer was Zone.js, and understanding it in one paragraph makes the new answer obvious.

Zone.js replaced every browser API that could possibly lead to a change — setTimeout, addEventListener, fetch, XMLHttpRequest, promises — with a wrapped version. After any of them finished, it told Angular: something asynchronous just completed, so something may have changed.

Angular then did the only thing it could: re-check every binding in every component, top to bottom, and compare each one against its previous value.

That works. It also means one keystroke in one input causes a full sweep of the entire component tree. On a screen with two thousand bindings, it is two thousand comparisons for one character.

Signals replace the guess with a fact.

Zone.js: one click, check everything root header list row footer 5 of 5 components re-checked Signals: only readers are notified count signal read by badge total footer 2 of 3 re-rendered; footer untouched
Figure 2 — The same click under two models. Zone.js knows only that something happened, so it re-checks the whole tree. A signal knows exactly who read it, so only those consumers are marked for re-render.

Creating and reading a signal

A signal is created by calling signal(initialValue). You read it by calling it like a function, and that pair of parentheses is the whole trick — it is the moment Angular records "whoever is rendering right now depends on this value."

Step-by-step: what counter.ts does, in plain English
  1. Import signal and computed from Angular's core package. Both are plain functions, not decorators.
  2. Create count by calling signal(0). The variable now holds a box containing the number zero, not the number itself.
  3. Create doubled by calling computed(...) with a function that reads count(). Angular notices the read and records the dependency: doubled depends on count.
  4. Define increment(). It calls count.update(...) with a function from the old value to the new one — the safe way to change a value that depends on itself.
  5. Define reset(). It calls count.set(0), which replaces the value outright — used when the new value does not depend on the old.
  6. In the template, count() and doubled() are read with parentheses. Each read subscribes this template to that signal for as long as the component lives.
  7. When increment() runs, count notifies its dependents. doubled marks itself stale, the template marks itself dirty, and Angular re-renders this component — and only this component.
src/app/counter/counter.tsruns offline
import { Component, signal, computed } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}</p>
    <p>Doubled: {{ doubled() }}</p>
    <button (click)="increment()">+1</button>
    <button (click)="reset()">Reset</button>
  `,
})
export class Counter {
  // A writable signal. Read it with count(), never count.
  readonly count = signal(0);

  // A derived signal. Angular recomputes it only when count changes.
  readonly doubled = computed(() => this.count() * 2);

  increment(): void {
    // update() takes the old value and returns the new one.
    this.count.update(n => n + 1);
  }

  reset(): void {
    // set() replaces the value outright.
    this.count.set(0);
  }
}

Read the template. {{ count() }} has parentheses; {{ count }} would display the function itself and print something like function computed(){...} on the screen. That missing pair of parentheses is the first mistake everyone makes, and the symptom is unmistakable once you have seen it.

Notice also readonly count. The signal box never gets reassigned; only its contents change. Marking it readonly stops you from accidentally replacing the box, which would silently break every existing subscription.

The three functions, and when to reach for each

Table 6 — The signal API you will use every day
FunctionWhat it makesReach for it when
signal(v) A writable box, with .set() and .update() This is a source of truth someone edits — a filter, a form value, a loaded list
computed(fn) A read-only box whose value is derived from other signals The value can always be calculated from other state. Filtered lists, totals, "is the form valid"
effect(fn) Not a value — a side effect that re-runs when its dependencies change You must reach outside Angular: log, save to localStorage, call a charting library

The decision between the first two is worth stating as a rule, because getting it wrong is the most common design mistake in signal-based Angular.

If a value can be calculated from other values, it is a computed, never a signal you keep in step by hand.

The moment you write two signals and remember to update the second whenever you update the first, you have created a bug that will eventually escape. Derive it instead.

derived-state.ts — the same screen, twiceruns offline
// WRONG: two sources of truth, kept in step by hand.
readonly tasks = signal<Task[]>([]);
readonly openCount = signal(0);           // must be updated everywhere tasks is

addTask(t: Task) {
  this.tasks.update(list => [...list, t]);
  this.openCount.update(n => n + 1);      // forget this line once and the badge lies
}

// RIGHT: one source of truth, everything else derived.
readonly tasks = signal<Task[]>([]);
readonly openCount = computed(() => this.tasks().filter(t => !t.done).length);

addTask(t: Task) {
  this.tasks.update(list => [...list, t]);   // openCount cannot fall out of step
}

Read the second version. There is no line that maintains openCount, so there is no line to forget. The count is a question asked of the list, not a number stored beside it.

computed is also lazy and cached. The filter does not run when tasks changes — it runs the next time somebody actually reads openCount(), and only if the underlying data really changed. If nothing on screen displays it, it never runs at all.

The mutation trap — the bug you will hit this week

Signals compare the old and new value with Object.is, which for objects and arrays means comparing identities, not contents.

Push an item into an array held by a signal and the array's identity has not changed. It is the same array. So the signal concludes nothing happened, and your screen does not update.

mutation-trap.tsruns offline
readonly tasks = signal<Task[]>([]);

// BROKEN -- the screen never updates.
addTask(t: Task) {
  this.tasks().push(t);        // mutates the array in place. Same array, same identity.
}

// CORRECT -- a new array, so a new identity, so notification fires.
addTask(t: Task) {
  this.tasks.update(list => [...list, t]);
}

// Same rule for objects. Spread, then override the field you are changing.
toggle(id: number) {
  this.tasks.update(list =>
    list.map(t => t.id === id ? { ...t, done: !t.done } : t)
  );
}

Read the last function. map returns a new array. Inside it, the matching task becomes a new object via { ...t, done: !t.done }, and the other tasks are passed through unchanged — same objects, same identities, so their rows are not re-rendered.

That is the discipline in one sentence: replace, do not mutate. It costs a spread operator and it removes an entire category of "why is the screen stale" bugs.

🧠 Brain power

You have readonly total = computed(() => this.items().reduce((s, i) => s + i.price, 0)); and a component template that never displays total(). You then call items.set(bigNewArray) with fifty thousand items. How many times does the reduce run?

Think first, then open

Zero times.

computed is lazy. Setting items marks total as stale — a flag flip, nothing more. The reduce only runs when somebody calls total(), and nobody does.

If you then display it, the reduce runs once and the result is cached. Reading total() a hundred more times costs nothing until items changes again.

This is why deriving with computed is cheap even for expensive calculations, and why calling the same expensive method from a template is not — a method has no dependency tracking and no cache, so it runs on every single render.

effect — and why you should reach for it less than you think

An effect runs a function whenever any signal it reads changes. It produces no value; it exists to cause something outside Angular to happen.

effects.tsruns offline
import { Component, signal, effect } from '@angular/core';

export class ThemePicker {
  readonly theme = signal<'light' | 'dark'>('light');

  constructor() {
    // Runs once immediately, then again on every change to theme.
    // Cleaned up automatically when the component is destroyed.
    effect(() => {
      localStorage.setItem('theme', this.theme());
      document.body.dataset['theme'] = this.theme();
    });
  }
}

Effects are the correct tool for exactly this: writing to storage, syncing a third-party library, logging, setting a document title.

They are the wrong tool for deriving state. An effect that reads signal A and calls b.set(...) is a computed written the hard way — it runs later, it is harder to test, it can loop, and Angular will warn you about writing to signals inside effects.

The rule: if the effect ends by setting another signal, you wanted computed.

linkedSignal — writable, but with a default that follows something else

There is one case computed cannot cover: a value the user can edit, which should also reset when its source changes.

A quantity selector on a product page is the classic example. The user can type a quantity, but switching to a different product should reset it to one.

linked-signal.tsruns offline
import { signal, linkedSignal } from '@angular/core';

readonly selectedProduct = signal<Product>(firstProduct);

// Writable like a signal, but recomputes from the source when the source changes.
readonly quantity = linkedSignal(() => {
  this.selectedProduct();   // declares the dependency
  return 1;                 // the value to fall back to
});

// The user types 5:            quantity.set(5)     -> 5
// The user picks a new product: selectedProduct.set(other) -> quantity is 1 again

Before linkedSignal existed, this pattern needed an effect that wrote to a signal — the thing you are told not to do. Now it is one call, and it is the right answer whenever you catch yourself wanting an effect to reset a field.

Quick reference — Signals

What a signal is
A value in a box that records who reads it and notifies them when it changes. Read with parentheses: count().
set vs update
set(v) replaces the value. update(fn) computes the new value from the old one — use it whenever the new value depends on the current one.
computed
Derived, read-only, lazy and cached. If a value can be calculated from other state, it belongs here. Never keep two signals in step by hand.
effect
Re-runs a side effect when its dependencies change. For reaching outside Angular only. If it ends by setting a signal, you wanted computed.
linkedSignal
Writable, but resets from a source when that source changes. The right tool for "user-editable with a default that follows something else".
The mutation trap
Signals compare with Object.is. arr.push() does not change the array's identity, so nothing updates. Replace with [...list, item] and { ...obj, field: v }.
Why this replaced Zone.js
Zone.js patched browser APIs to guess that something changed, forcing a whole-tree re-check. A signal knows precisely which components read it, so only those re-render.

06 · CompositionTalking Between Components — Down With Inputs, Up With Outputs

A parent passes data down to a child through inputs. A child reports events up to its parent through outputs. Data flows down, events flow up, and that one-way rule is what keeps a large Angular app understandable.

Your application is a tree of components. The page holds a list, the list holds rows, a row holds a badge. Each of those is a component, and they must exchange information.

Angular gives you exactly two channels, and their directions are fixed on purpose.

Inputs — data flowing down

An input is a property of a child component that the parent sets from its template. You declare it by calling input().

Step-by-step: what task-card.ts does with its inputs, in plain English
  1. Import input from Angular core — a function, like signal.
  2. Declare task = input.required<Task>(). The .required form means the parent must supply it, and Angular fails the build if it does not.
  3. Declare compact = input(false). Passing a default makes it optional; its type is inferred as boolean from that default.
  4. Read both in the template with parentheses — task(), compact(). Inputs are signals, so reading one subscribes the template to it.
  5. Derive label with computed, reading task(). When the parent passes a new task, the input signal changes and the label recomputes automatically.
  6. Nothing in the class ever writes to task. Inputs are read-only by design: the parent owns the value, the child only displays it.
src/app/task-card/task-card.ts — the childruns offline
import { Component, input, computed } from '@angular/core';
import { Task } from '../task.model';

@Component({
  selector: 'app-task-card',
  template: `
    <article [class.compact]="compact()">
      <h3>{{ task().title }}</h3>
      <p>{{ label() }}</p>
    </article>
  `,
})
export class TaskCard {
  // Required: the parent must pass it, checked at build time.
  readonly task = input.required<Task>();

  // Optional, with a default. Type inferred as boolean.
  readonly compact = input(false);

  // Inputs are signals, so computed() reacts to them like any other signal.
  readonly label = computed(() => this.task().done ? 'Done' : 'Open');
}
the parent's templateruns offline
<!-- Square brackets bind an expression. Without them you pass the literal string. -->
<app-task-card [task]="currentTask()" [compact]="true" />

<!-- In a loop, each card gets its own task -->
@for (t of tasks(); track t.id) {
  <app-task-card [task]="t" />
}

Read the binding syntax once more. [task]="t" passes the value of the expression t. Writing task="t" without brackets would pass the two-character string "t", and TypeScript would reject it because a string is not a Task. That rejection is a feature.

Transforming and renaming an input

input() takes options that solve two recurring annoyances.

input-options.tsruns offline
import { input, booleanAttribute, numberAttribute } from '@angular/core';

// transform: convert whatever the parent passed into the type you want.
// booleanAttribute turns "" and "true" into true -- so <app-x disabled /> works.
readonly disabled = input(false, { transform: booleanAttribute });

// numberAttribute turns the string "5" into the number 5.
readonly pageSize = input(10, { transform: numberAttribute });

// alias: the public name differs from the internal one.
readonly value = input(0, { alias: 'count' });   // parent writes [count]="n"

Use booleanAttribute whenever you want a flag the parent can set by presence alone, the way native HTML does with <input disabled>. Without it, <app-x disabled /> passes the empty string, which is falsy, and the flag silently never turns on.

Outputs — events flowing up

An output is a channel a child uses to tell its parent that something happened. You declare it with output() and fire it with .emit(value).

task-card.ts — adding an outputruns offline
import { Component, input, output } from '@angular/core';

@Component({
  selector: 'app-task-card',
  template: `
    <h3>{{ task().title }}</h3>
    <button (click)="toggled.emit(task().id)">Toggle</button>
    <button (click)="deleted.emit(task().id)">Delete</button>
  `,
})
export class TaskCard {
  readonly task = input.required<Task>();

  // The generic says what value travels up the channel.
  readonly toggled = output<number>();
  readonly deleted = output<number>();
}
the parent listensruns offline
<!-- $event is whatever the child passed to emit() -- here, the task id -->
<app-task-card
  [task]="t"
  (toggled)="onToggle($event)"
  (deleted)="onDelete($event)" />

$event is not magic and not global. It is the name Angular gives to the emitted value inside an event binding. For a DOM event like (click) it is the browser's event object; for a custom output it is exactly the argument passed to emit().

Why the child does not just change the data itself

A fair question, and the answer is the design principle of the whole framework.

The child could mutate the task object it was handed. Nothing in JavaScript stops it. And then, six months later, a row is toggling itself and nobody can find where — because any of forty components might be the one writing.

When the child only emits, there is exactly one place in the codebase that changes a task: the parent's handler. Debugging becomes reading one function instead of searching a tree.

This is called unidirectional data flow, and it is the same reason a database has one writer per row.

TaskList (parent) owns tasks = signal<Task[]> [task]="t" data down (toggled)="onToggle($event)" events up TaskCard (child) reads task(), emits toggled The child never writes the task. One writer, one place to debug.
Figure 3 — Unidirectional data flow. The parent owns the state and passes a read-only view down; the child reports intent upward and the parent decides what to do about it.

model() — two-way binding, when it is genuinely the right shape

Sometimes down-then-up is ceremony. A custom rating widget or a search box is a value the parent owns and the child edits, and writing an input plus an output plus a handler for it is three pieces of code for one idea.

model() creates a writable signal that is bound both ways.

rating.tsruns offline
import { Component, model } from '@angular/core';

@Component({
  selector: 'app-rating',
  template: `
    @for (star of [1,2,3,4,5]; track star) {
      <button (click)="value.set(star)">{{ star <= value() ? '★' : '☆' }}</button>
    }
  `,
})
export class Rating {
  readonly value = model(0);   // readable, writable, and bound to the parent
}
the parent — banana in a boxruns offline
<!-- [(value)] is shorthand for [value]="score()" (valueChange)="score.set($event)" -->
<app-rating [(value)]="score" />

<p>You rated it {{ score() }} out of 5.</p>

Use model() for form-like widgets, where "the parent holds a value and the child edits it" is the honest description. Use input plus output everywhere else, because it keeps the writer count at one.

Content projection — letting the parent supply the markup

Inputs pass data. Sometimes you want to pass markup — a card component that lays out a border and a shadow, but lets each caller decide what goes inside.

That is content projection, and the tag is <ng-content>.

panel.ts and its useruns offline
@Component({
  selector: 'app-panel',
  template: `
    <section class="panel">
      <header><ng-content select="[panel-title]" /></header>
      <div class="body"><ng-content /></div>
    </section>
  `,
})
export class Panel {}
the caller fills the slotsruns offline
<app-panel>
  <h2 panel-title>Overdue tasks</h2>

  <p>Anything not matching a select lands in the unnamed slot.</p>
  <app-task-card [task]="t" />
</app-panel>

The select attribute takes a CSS selector and routes matching children into that slot. Anything unmatched falls into the plain <ng-content />.

This is how every component library builds layout shells — cards, dialogs, tabs, accordions. The shell owns the structure; the caller owns the contents.

The old decorator syntax, for reading legacy files

Table 7 — Old decorators and the modern signal-based equivalents
Old (Angular 2–16)Modern (Angular 17+)What changed for you
@Input() task!: Task; task = input.required<Task>(); Read with task(). Required-ness is checked at build time instead of hoped for.
@Output() toggled = new EventEmitter<number>(); toggled = output<number>(); Same .emit(), but no RxJS Subject underneath and cleanup is automatic.
ngOnChanges(changes: SimpleChanges) computed() or effect() reading the input No string-keyed change object, no manual comparison of previous and current values.
@ViewChild('x') el!: ElementRef; el = viewChild<ElementRef>('x'); A signal that is undefined until the view exists, rather than a field that is undefined until a lifecycle hook fires.

The pattern across that table is one idea: lifecycle hooks are being replaced by reactivity. Instead of being told "an input changed, go and look", you write a derivation that is simply always correct.

Quick reference — Component communication

input() / input.required()
Data from parent to child. It is a read-only signal; read it with parentheses. Required inputs are enforced at build time.
transform
booleanAttribute makes <app-x disabled /> work; numberAttribute turns "5" into 5.
output()
Events from child to parent. Fire with .emit(value); the parent receives it as $event.
Unidirectional data flow
Data down, events up. The owner of the state is the only writer, so a wrong value has exactly one place to be wrong.
model()
A two-way bound writable signal, used by the parent as [(value)]. Right for form widgets; wrong as a general shortcut.
<ng-content />
Projects markup supplied by the caller. select="[attr]" creates named slots; the unnamed one catches the rest.

07 · The third ideaServices & Dependency Injection — Asking Instead of Building

A service is an ordinary class holding data or logic that more than one component needs. Dependency injection is how a component gets hold of one: it asks the framework, and the framework hands over the shared instance.

Two components need the same list of tasks. Where does the list live?

Not in either component — whichever one you choose, the other has to reach across and grab it, and when a third component appears you have a triangle.

The list lives in a service: a plain class whose job is to hold the data and the operations on it. Components ask for the service and read from it.

Writing your first service

terminalruns offline
ng generate service task
# CREATE src/app/task.ts
# CREATE src/app/task.spec.ts
Step-by-step: what task.ts does, in plain English
  1. Import Injectable and signal/computed from Angular core.
  2. Apply @Injectable({ providedIn: 'root' }). This label says two things: this class can be injected, and Angular should create exactly one instance for the whole application, on first use.
  3. Hold the state in a private writable signal, _tasks. Private means no component can call .set() on it from outside.
  4. Expose a public read-only view with .asReadonly(). Components can read every value but cannot write any.
  5. Expose derived values — openCount, doneCount — as computed. They are always correct because they are questions asked of the list.
  6. Provide methods that are the only way to change the list: add, toggle, remove. Each replaces the array rather than mutating it, so the signal notifies.
  7. Because providedIn: 'root' makes this a single shared instance, every component that injects it sees the same signals and therefore the same data.
src/app/task.ts — a signal store, which is what most services now areruns offline
import { Injectable, signal, computed } from '@angular/core';
import { Task } from './task.model';

@Injectable({ providedIn: 'root' })   // one instance for the whole application
export class TaskService {
  // Private source of truth. Nothing outside this class can write it.
  private readonly _tasks = signal<Task[]>([]);

  // Public, read-only view of the same signal.
  readonly tasks = this._tasks.asReadonly();

  readonly openCount  = computed(() => this._tasks().filter(t => !t.done).length);
  readonly doneCount  = computed(() => this._tasks().filter(t =>  t.done).length);
  readonly isEmpty    = computed(() => this._tasks().length === 0);

  add(title: string): void {
    const task: Task = {
      id: Date.now(),
      title,
      done: false,
      createdAt: new Date().toISOString(),
    };
    this._tasks.update(list => [...list, task]);
  }

  toggle(id: number): void {
    this._tasks.update(list =>
      list.map(t => t.id === id ? { ...t, done: !t.done } : t)
    );
  }

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

Read the private-plus-asReadonly pattern. It is the most valuable habit in this entire chapter.

Every component can read tasks(). No component can call tasks.set(...), because the public handle has no set. Changes happen only through add, toggle and remove.

So when a task appears with the wrong title, there are three functions that could have done it — not forty components. That is the whole benefit, and it costs one extra line.

Getting hold of it: inject()

task-list.ts — asking for the serviceruns offline
import { Component, inject } from '@angular/core';
import { TaskService } from '../task';

@Component({
  selector: 'app-task-list',
  template: `
    <p>{{ store.openCount() }} open, {{ store.doneCount() }} done</p>

    @for (t of store.tasks(); track t.id) {
      <li>
        <input type="checkbox" [checked]="t.done" (change)="store.toggle(t.id)">
        {{ t.title }}
        <button (click)="store.remove(t.id)">×</button>
      </li>
    } @empty {
      <p>Nothing yet.</p>
    }
  `,
})
export class TaskList {
  // One line. No constructor needed.
  protected readonly store = inject(TaskService);
}

inject(TaskService) reads as what it is: "give me the TaskService". Angular looks it up, creates it if this is the first request, and returns the shared instance.

protected is the right modifier for anything a template uses. It stops other classes from reaching in, while still allowing the component's own template to read it — Angular's compiler treats the template as part of the class.

Constructor injection, which you will still read everywhere

the older equivalentruns offline
export class TaskList {
  // Identical result. Angular reads the parameter's type and supplies the instance.
  constructor(private store: TaskService, private router: Router) {}
}

Both forms work and both are supported. inject() has three practical advantages, which is why new code uses it.

One rule binds it: inject() may only be called during construction — as a field initialiser or inside the constructor body. Calling it inside a click handler throws NG0203, because by then Angular no longer knows which component is asking.

How Angular finds what you asked for

Dependency injection is a lookup. When a component calls inject(X), Angular searches a chain of injectors — registries of "how to build things" — from the most specific to the most general, and stops at the first one that knows about X.

TaskList component providers: [] — nothing here not found, go up BoardPage component providers: [FilterService] still not found Root injector providedIn: 'root' services inject(TaskService) found at the root → one shared instance, the same object for every component. inject(FilterService) found at BoardPage → a fresh instance per BoardPage, destroyed with it. inject(Missing) reaches the top with no provider → NG0201: No provider for Missing.
Figure 4 — The injector chain. The search runs upward from the component and stops at the first level that provides the token, which is exactly how you control whether a service is shared or per-component.

That search order gives you a design lever, and it is the answer to a question every Angular developer eventually asks.

Table 8 — Where to provide a service, and what you get
WhereHow many instancesLives untilChoose it when
@Injectable({ providedIn: 'root' }) One, for the whole app The tab closes Shared state, HTTP wrappers, auth, logging — the default choice
providers: [X] in a component One per instance of that component That component is destroyed State that belongs to one screen and must reset when you leave it
providers: [X] on a route One per activation of that route subtree You navigate away from the subtree Feature-scoped state shared by several sibling screens
providers: [X] in appConfig One, for the whole app The tab closes Third-party classes you cannot decorate, and configuration values

The trap worth naming. Putting a service in a component's providers array gives every instance of that component its own copy.

Do that with a service you meant to share, render the component in a loop, and you get twenty independent stores that each hold a fifth of the truth. The symptom is a screen where one panel updates and its neighbour does not.

Providing something that is not a class

inject(TaskService) works because a class is its own lookup key. A configuration string has no class, so it needs an explicit key: an injection token.

tokens.tsruns offline
import { InjectionToken, inject } from '@angular/core';

export interface ApiConfig { baseUrl: string; timeoutMs: number; }

// The string is only for error messages; the object identity is the real key.
export const API_CONFIG = new InjectionToken<ApiConfig>('API_CONFIG');

// In app.config.ts:
providers: [
  { provide: API_CONFIG, useValue: { baseUrl: '/api', timeoutMs: 8000 } },
]

// Anywhere in the app:
const config = inject(API_CONFIG);   // typed as ApiConfig, no casting

The four provider recipes are worth knowing by name, because they appear in every real app.config.ts.

Table 9 — The provider recipes
RecipeMeaningTypical use
useClassBuild this class when that token is asked forSwapping a real implementation for a fake in tests
useValueHand back this exact objectConfiguration, constants, feature flags
useFactoryRun this function and hand back what it returnsA value that depends on the environment or on other services
useExistingAlias: give back whatever that other token givesExposing one service under a narrower interface
New in Angular 22 — the @Service() decorator

Angular 22 added @Service() as a shorter spelling of the overwhelmingly common case. Writing @Service() means the same as @Injectable({ providedIn: 'root' }), and @Service({ autoProvided: false }) covers the case where you provide it yourself.

This chapter teaches @Injectable because that is what every existing codebase and every existing answer uses, and because knowing the long form makes the short one obvious. Use whichever your team has standardised on; they produce identical behaviour.

Why this is worth the ceremony at all

A fair objection: you could export a single object from a module and import it, and get one shared instance with no framework involved.

You could, and for a small app it would be fine. Dependency injection buys three things that matter as the app grows.

It makes tests easy. A test provides a fake TaskService with useClass, and the component under test never knows the difference. With a hard import there is no seam to substitute at.

It makes lifetime a decision. Moving one service from root to a route's providers changes it from "lives forever" to "resets when you leave this feature", and no component's code changes.

It makes configuration late. The same component can run against a real API in production and a stub in a demo, decided in app.config.ts rather than in the component's imports.

Quick reference — Services and DI

Service
An ordinary class holding shared state or logic. Marked @Injectable({ providedIn: 'root' }), or @Service() in Angular 22.
inject(X)
Ask for a dependency. Only callable during construction — a field initialiser or the constructor body. Elsewhere it throws NG0203.
Injector chain
The search runs from the component upward to the root and stops at the first provider found. NG0201 means it reached the top with nothing.
providedIn: 'root' vs component providers
Root gives one shared instance for the app. A component's providers array gives one instance per component instance — a silent bug when you meant to share.
Private signal + asReadonly()
The standard store shape. Everyone reads, only the service's own methods write, so a wrong value has few places to come from.
InjectionToken
A lookup key for things that are not classes — configuration objects, strings, functions — with the type carried along.
Provider recipes
useClass substitute, useValue constant, useFactory computed, useExisting alias.

08 · Real dataTalking to a Server — httpResource, HttpClient, and Just Enough RxJS

Angular ships an HTTP client. In Angular 22 the easy path is httpResource, which turns a URL into a set of signals — the data, whether it is loading, and any error — with no subscribing to manage.

Everything so far kept data in memory. Real applications fetch it, and fetching introduces the two problems that make frontend code hard.

The first is time: the data is not there yet, so the screen must show something meaningful in the meantime. The second is failure: the request can fail, and the screen must say so rather than sitting blank.

A good data-fetching API forces you to handle all three states. Angular's does.

Switch the HTTP client on

src/app/app.config.tsruns offline
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(),      // <- now HttpClient and httpResource can be injected
  ],
};

Forgetting this line produces NG0201: No provider for _HttpClient, which is the single most-seen Angular error after a fresh install. The chain search reached the root and found nothing, exactly as Figure 4 showed.

The modern way: httpResource

A resource is Angular's name for "an asynchronous value modelled as signals". httpResource is the HTTP flavour: you give it a function returning a URL, and you get back an object of signals.

Step-by-step: what task-page.ts does, in plain English
  1. Import httpResource from @angular/common/http, plus signal and Component from core.
  2. Create filter, a writable signal holding the current search text. This is what the user edits.
  3. Create tasksResource by calling httpResource with a function that builds a URL by reading filter(). Reading it inside the function registers the dependency.
  4. Because the URL function depends on filter, changing the filter automatically triggers a new request. There is no code that says "when the filter changes, refetch" — the dependency is the trigger.
  5. Pass { defaultValue: [] } so the value is an empty array before the first response, rather than undefined. This removes a whole class of null checks from the template.
  6. In the template, read tasksResource.isLoading() first and show a spinner. Then read tasksResource.error() and show a message. Only then render tasksResource.value().
  7. Give the retry button tasksResource.reload(), which re-runs the request with the same inputs.
  8. Angular cancels an in-flight request automatically if the inputs change again before it lands, so fast typing cannot deliver a stale response after a fresh one.
src/app/task-page/task-page.tsruns offline
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Task } from '../task.model';

@Component({
  selector: 'app-task-page',
  template: `
    <input [value]="filter()" (input)="filter.set($any($event.target).value)"
           placeholder="Search tasks">

    @if (tasksResource.isLoading()) {
      <p>Loading…</p>
    } @else if (tasksResource.error()) {
      <p class="error">Could not load tasks.</p>
      <button (click)="tasksResource.reload()">Retry</button>
    } @else {
      <ul>
        @for (t of tasksResource.value(); track t.id) {
          <li>{{ t.title }}</li>
        } @empty {
          <li>No tasks matched.</li>
        }
      </ul>
    }
  `,
})
export class TaskPage {
  readonly filter = signal('');

  // Reading filter() inside makes this resource re-fetch whenever the filter changes.
  readonly tasksResource = httpResource<Task[]>(
    () => `/api/tasks?q=${encodeURIComponent(this.filter())}`,
    { defaultValue: [] }
  );
}

Read what is not in that file. There is no subscribe, no unsubscribe, no ngOnDestroy, no loading = true flag set in two places, and no code connecting the filter to the request.

The dependency is the wiring. That is the same idea as computed, extended over the network.

Table 10 — What a resource gives you
MemberTypeWhat it holds
value()Signal of your dataThe last successful response, or the defaultValue
isLoading()Signal of booleanTrue while a request is in flight
error()Signal of the error or undefinedSet when the request failed
status()Signal of a status string'idle', 'loading', 'reloading', 'error', 'resolved', 'local'
reload()MethodRuns the request again with the same inputs

resource() is the general form — it takes any async function, not just an HTTP call — and rxResource() takes a function returning an Observable. All three became stable in Angular 22.

HttpClient — for anything you are sending, not fetching

Resources model reads. A write — creating a task, deleting one — is something you do once, at a moment of your choosing, and it does not belong in a declarative dependency graph.

For those, inject HttpClient directly.

src/app/task-api.tsruns offline
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Task } from './task.model';

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

  // The generic tells TypeScript what the JSON will parse into.
  // Angular does NOT check this at runtime -- it is a promise you are making.
  create(title: string): Observable<Task> {
    return this.http.post<Task>('/api/tasks', { title, done: false });
  }

  remove(id: number): Observable<void> {
    return this.http.delete<void>(`/api/tasks/${id}`);
  }

  list(): Observable<Task[]> {
    return this.http.get<Task[]>('/api/tasks', {
      params: { limit: 50 },       // becomes ?limit=50, correctly encoded
    });
  }
}

The generic is a claim, not a check. get<Task[]> tells the compiler to treat the response as an array of tasks. If the server sends something else, nothing complains until a property is undefined three components away. Validate at the boundary if the API is not yours.

The one RxJS fact you need right now

Those methods return an Observable, not a promise. Here is the minimum you need, with the rest deferred to Chapter E15.

An observable is a recipe for producing values over time. Two consequences follow, and they cause most beginner surprises.

It is lazy. Calling this.http.get(...) sends no request at all. Nothing happens until something subscribes. This is the opposite of a promise, which starts immediately.

It can produce many values. An HTTP observable happens to emit once and complete, but the type does not know that — which is why it has cancellation, retries and operators that a promise does not.

subscribing to a writeruns offline
addTask(title: string): void {
  this.api.create(title).subscribe({
    next:  (created) => this.store.insert(created),
    error: (err)     => this.errorMessage.set('Could not save. Try again.'),
  });
}

You do not need to unsubscribe from an HttpClient call. It completes after one value, and a completed observable releases its subscription.

You do need to unsubscribe from anything that never completes — a router event stream, an interval, a WebSocket. The tool for that is takeUntilDestroyed(), and Chapter E15 covers it properly.

Bridging an observable into a signal

Most of your app is signals, and sometimes a library hands you an observable. toSignal() converts one, and handles the subscription and cleanup for you.

interop.tsruns offline
import { toSignal } from '@angular/core/rxjs-interop';

// Subscribes on creation, unsubscribes when the component is destroyed.
readonly tasks = toSignal(this.api.list(), { initialValue: [] as Task[] });

// In the template: {{ tasks().length }} -- an ordinary signal from here on.

The older equivalent is the async pipe in the template — @if (tasks$ | async; as tasks). It still works and you will read a lot of it. toSignal is preferred in new code because the value is then available in the class too, not just in the template.

Interceptors — one place for headers, errors and retries

An interceptor is a function every HTTP request passes through. It is where authentication headers, logging, and global error handling belong, so that no individual call has to remember them.

src/app/auth.interceptor.tsruns offline
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, throwError } from 'rxjs';
import { AuthService } from './auth';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();

  // Requests are immutable. clone() with the change you want.
  const authed = token
    ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
    : req;

  return next(authed).pipe(
    catchError((err) => {
      if (err.status === 401) {
        inject(AuthService).logout();
      }
      return throwError(() => err);   // pass it on; do not swallow it
    })
  );
};
register it in app.config.tsruns offline
provideHttpClient(
  withInterceptors([authInterceptor, loggingInterceptor]),
),

Requests are immutable on purpose. You cannot set a header on req; you call req.clone(...) and pass the copy onward. That guarantees a retry re-sends exactly the request that was originally made, not one an interceptor edited halfway through.

Interceptors run in the order you list them on the way out, and in reverse on the way back — the same shape as middleware in Spring's filter chain.

Failure mode — the three-state screen nobody built

The most common defect in production Angular is not a crash. It is a screen that shows an empty list when the request failed, because the template only handled "have data" and "do not have data yet".

A user cannot tell "you have no tasks" from "we could not reach the server". They conclude their data is gone and they file a support ticket.

Every screen that fetches has three states, and a fourth that is worth separating: loading, error, empty-but-successful, and populated. httpResource gives you the signals for all four, and the template in this section handles each one. Copy that shape.

Quick reference — HTTP

provideHttpClient()
Required in app.config.ts. Its absence is NG0201 "No provider for _HttpClient".
httpResource(urlFn, opts)
Turns a URL into signals: value, isLoading, error, status, plus reload(). Re-fetches when any signal read inside urlFn changes, and cancels the previous request.
resource / rxResource
The same idea over any async function, or over an Observable. All three stable in Angular 22.
HttpClient
For writes and one-off calls. get<T> is a compile-time claim about the JSON, never a runtime check.
Observables are lazy
No request is sent until something subscribes. HTTP observables complete after one value, so they need no manual unsubscribe.
toSignal(obs$, { initialValue })
Bridges an observable into a signal, subscribing and cleaning up automatically. Preferred over the async pipe in new code.
Interceptors
Functions in withInterceptors([...]). Clone the request to add headers; never mutate it. Out in order, back in reverse.
Four screen states
Loading, error, empty, populated. An error rendered as an empty list is the most common production defect on data screens.

09 · The fourth ideaRouting — Which Components Are On Screen For This URL

The router is a lookup table from URL patterns to components. It swaps components in and out of a placeholder tag, updates the address bar, and never reloads the page.

A single-page application loads one HTML file. So "navigating to /tasks/42" cannot mean fetching a new page — it means rendering different components and telling the browser to display a different URL.

That is the router's whole job, and it has three moving parts: a table, a placeholder, and links.

The table

src/app/app.routes.tsruns offline
import { Routes } from '@angular/router';
import { TaskList } from './task-list/task-list';

export const routes: Routes = [
  // Eagerly loaded: this component is in the initial bundle.
  { path: '', component: TaskList, title: 'Tasks' },

  // Lazily loaded: downloaded only when the user first visits it.
  {
    path: 'tasks/:id',
    loadComponent: () => import('./task-detail/task-detail').then(m => m.TaskDetail),
    title: 'Task detail',
  },

  // A whole feature area, lazily loaded as one chunk.
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
  },

  // Redirect. pathMatch: 'full' means the WHOLE url must be empty, not just the start.
  { path: 'home', redirectTo: '', pathMatch: 'full' },

  // Wildcard. Must be last -- the router takes the first match, in order.
  { path: '**', loadComponent: () => import('./not-found/not-found').then(m => m.NotFound) },
];

Order matters and it is not by specificity. The router walks the array from the top and takes the first path that matches. Put ** anywhere but last and it swallows everything below it.

:id is a route parameter — a named blank that matches one URL segment. /tasks/42 and /tasks/99 both match, with id being '42' or '99'. Route parameters are always strings.

The placeholder and the links

src/app/app.htmlruns offline
<nav>
  <!-- routerLink navigates without reloading. href would reload the whole app. -->
  <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Tasks</a>
  <a routerLink="/admin" routerLinkActive="active">Admin</a>

  <!-- Array form builds the URL from parts; each part is escaped for you. -->
  <a [routerLink]="['/tasks', task.id]">Open</a>
</nav>

<!-- The matched component is rendered here, replacing whatever was here before. -->
<router-outlet />
src/app/app.ts — the directives must be importedruns offline
import { Component } from '@angular/core';
import { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, RouterLink, RouterLinkActive],   // standalone: declare your own
  templateUrl: './app.html',
})
export class App {}

routerLink, never href. An href makes the browser throw away your entire application and download it again — losing every signal, every service instance, and about two seconds. routerLink swaps components in place.

Forgetting to add RouterLink to imports is the classic standalone mistake. The symptom is quiet: the link renders, but clicking it does nothing, because routerLink was treated as an unknown attribute.

Reading route parameters — the good way

The old way injects ActivatedRoute and subscribes to an observable of parameters. The modern way is one line of configuration and then nothing at all.

app.config.ts — turn it on onceruns offline
provideRouter(routes, withComponentInputBinding()),
task-detail.ts — the parameter arrives as an inputruns offline
import { Component, input, computed } from '@angular/core';
import { httpResource } from '@angular/common/http';

@Component({
  selector: 'app-task-detail',
  template: `
    @if (task.isLoading()) { <p>Loading…</p> }
    @else if (task.value(); as t) { <h1>{{ t.title }}</h1> }
  `,
})
export class TaskDetail {
  // Matches the :id in the route path. Always a string.
  readonly id = input.required<string>();

  readonly task = httpResource<Task>(() => `/api/tasks/${this.id()}`);
}

Read what happens on navigation. Going from /tasks/42 to /tasks/99 does not destroy the component — the router reuses it and changes the input. Because id is a signal, the resource's URL changes, and the fetch happens with no lifecycle hook involved.

Under the old ActivatedRoute.snapshot.params approach that same navigation was a well-known bug: the snapshot was read once in the constructor, the component was reused, and the page kept showing task 42 forever.

Query parameters bind the same way: ?page=2 arrives in an input named page.

Guards — deciding whether navigation is allowed

A guard is a function the router runs before activating a route. Return true to allow it, false to block it, or a UrlTree to redirect.

src/app/auth.guard.tsruns offline
import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from './auth';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (auth.isLoggedIn()) {
    return true;
  }

  // Returning a UrlTree redirects, and records where the user was going.
  return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url },
  });
};

// In the routes table:
{ path: 'admin', canActivate: [authGuard], loadChildren: ... }

Guards are plain functions now, not classes implementing an interface. They can use inject() because the router runs them inside an injection context.

The other guard worth knowing is canDeactivate, which asks a component whether it is willing to be left — the "you have unsaved changes" prompt.

A guard is not security

A route guard runs in the browser, in JavaScript the user can read and modify. It stops a normal person from reaching a screen. It does not stop anybody from calling your API.

Every guard must be matched by an authorisation check on the server, on every endpoint. The guard is a user-experience feature that prevents an ugly empty screen; the server is what actually enforces the rule. Interviewers ask this deliberately.

Why lazy loading matters, in numbers

loadComponent and loadChildren take a function returning a dynamic import(). The build tool sees that call and splits the code into a separate file, fetched on first visit.

Consider an app with a customer area and an admin area, roughly equal in size. Loaded eagerly, every customer downloads both, so a 900 KB bundle serves a 450 KB need.

Split lazily, the first page is 450 KB and the admin chunk is fetched only by the few people who open it. On a slow mobile connection that is the difference between a two-second and a four-second first render — and first render is the metric users judge you on.

The rule of thumb: lazy-load every feature area behind its own top-level route. The cost is one function; the benefit compounds with every feature you add.

Quick reference — Routing

Routes array
First match wins, top to bottom. ** must be last. redirectTo usually needs pathMatch: 'full'.
<router-outlet />
The placeholder where the matched component is rendered. Nested outlets render child routes.
routerLink vs href
routerLink swaps components in place. href reloads the whole application and throws away all state.
withComponentInputBinding()
Route and query parameters arrive as component inputs. Because inputs are signals, reusing a component across /tasks/42 → /tasks/99 just works.
Guards
Plain functions typed CanActivateFn. Return true, false, or a UrlTree to redirect. They are UX, never security — the server must check too.
loadComponent / loadChildren
Dynamic import() creates a separate bundle fetched on first visit. Lazy-load every top-level feature area.

10 · InputForms & Validation — Where Most Business Applications Actually Live

Angular has three form systems. Reactive forms are what almost every existing codebase uses; Signal Forms are the new one that became stable in Angular 22. This section teaches reactive forms properly and then shows what changes.

If you work on internal tools, banking, insurance or healthcare software, forms are the product. Everything else is navigation between forms.

A form has to hold values, validate them, know whether the user has touched a field, know whether the form as a whole may be submitted, and display errors only at moments that are not annoying. That is more state than it looks.

Reactive forms — the form is an object in your class

"Reactive" means the form's structure is defined in TypeScript, and the template binds to it. The class is the source of truth; the HTML is a view of it.

Step-by-step: what task-form.ts does, in plain English
  1. Import ReactiveFormsModule and add it to the component's imports. Without it, [formGroup] is an unknown attribute and the form silently does nothing.
  2. Inject FormBuilder, a helper that builds form objects with less typing than calling the constructors directly.
  3. Call fb.nonNullable.group({...}) to build the form. nonNullable means resetting a field returns it to its initial value rather than null, which removes a whole family of null checks.
  4. For each field, give the initial value and an array of validators. Validators.required and Validators.minLength(3) are built in.
  5. In the template, bind the <form> element with [formGroup]="form" and each input with formControlName="title", matching the key in the group.
  6. Bind (ngSubmit) rather than (click) on the button, so that pressing Enter in a text field also submits — which is what keyboard users expect.
  7. Show an error only when the control is invalid and the user has touched it, so a fresh empty form is not covered in red.
  8. In submit(), guard on form.invalid and call markAllAsTouched() before returning, so every error becomes visible at once instead of one at a time.
  9. On success, read form.getRawValue() — typed, and including any disabled controls that .value would omit.
src/app/task-form/task-form.tsruns offline
import { Component, inject, output } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-task-form',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <label for="title">Title</label>
      <input id="title" formControlName="title">

      @if (title.invalid && title.touched) {
        @if (title.hasError('required'))  { <p class="error">Title is required.</p> }
        @if (title.hasError('minlength')) { <p class="error">At least 3 characters.</p> }
      }

      <label for="due">Due date</label>
      <input id="due" type="date" formControlName="dueDate">

      <button type="submit" [disabled]="form.invalid">Add task</button>
    </form>
  `,
})
export class TaskForm {
  private readonly fb = inject(FormBuilder);
  readonly created = output<{ title: string; dueDate: string }>();

  readonly form = this.fb.nonNullable.group({
    title:   ['', [Validators.required, Validators.minLength(3)]],
    dueDate: [''],
  });

  // A getter keeps the template readable and correctly typed.
  get title() { return this.form.controls.title; }

  submit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();   // reveal every error at once
      return;
    }
    this.created.emit(this.form.getRawValue());
    this.form.reset();                // nonNullable: back to '', not null
  }
}

The four state flags, and the one that matters for error display

Every control and every group carries four booleans. Knowing which one to check is the difference between a form that feels considerate and one that feels hostile.

Table 11 — Control state, and what each flag actually means
FlagTrue whenUse it for
valid / invalidAll validators pass / any failsEnabling submit
touched / untouchedThe field has been focused and then blurredDeciding whether to show an error
dirty / pristineThe value has been changed by the user"Unsaved changes" warnings
pendingAn async validator is still runningA spinner beside the field

Show errors on touched, not on invalid alone. A required field is invalid the instant the form appears. Rendering that error immediately tells the user off for not having typed yet.

The considerate rule: complain after they leave a field, or after they try to submit. Never while they are still typing the first character.

Custom validators

A validator is a function that receives the control and returns null when everything is fine, or an object describing the problem when it is not.

validators.tsruns offline
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

// null means valid. An object means invalid, and its keys become error names.
export function noProfanity(banned: string[]): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const value = String(control.value ?? '').toLowerCase();
    const hit = banned.find(word => value.includes(word));
    return hit ? { profanity: { word: hit } } : null;
  };
}

// A cross-field validator goes on the GROUP, because it needs both controls.
export const datesInOrder: ValidatorFn = (group: AbstractControl) => {
  const start = group.get('start')?.value;
  const end   = group.get('end')?.value;
  return start && end && start > end ? { dateOrder: true } : null;
};

The returned object's keys are what hasError('profanity') checks, and its values are available for the message — title.getError('profanity').word gives you the offending word to show.

The three form systems, and which to use

Table 12 — Angular's form systems as of September 2026
SystemWhat it looks likeReach for it when
Reactive forms FormBuilder, [formGroup], formControlName Anything real. It is what nearly every existing codebase uses, and what interviews ask about
Template-driven [(ngModel)] plus FormsModule A two-field filter bar where a full form object is overkill. Hard to test and hard to validate across fields
Signal Forms form() over a signal, from @angular/forms/signals New code on Angular 22, where you want the form's state to be signals like everything else

Signal Forms, in brief

Signal Forms became stable in Angular 22. The idea: your data is already a signal, so the form should be a view over that signal rather than a parallel object you keep in step with it.

signal-form.ts — the new shaperuns offline
import { signal } from '@angular/core';
import { form, required, minLength } from '@angular/forms/signals';

// Your model is an ordinary signal -- the same one the rest of the app reads.
readonly model = signal({ title: '', dueDate: '' });

// The form wraps it and attaches rules per field.
readonly taskForm = form(this.model, (path) => {
  required(path.title);
  minLength(path.title, 3);
});

// taskForm.title().errors(), taskForm().valid() -- all signals.
// this.model() is always the current value. No getRawValue(), no sync step.

The gain is that there is one source of truth instead of two. In reactive forms, the form object holds the values and your component often holds a copy; keeping them aligned is a familiar chore.

What to learn first, honestly: reactive forms. They are in every codebase you will join and every interview you will sit. Learn Signal Forms second, and know that compatForm() exists so a large application can migrate one form at a time.

Quick reference — Forms

ReactiveFormsModule
Must be in the component's imports. Without it [formGroup] is inert and the form silently does nothing.
fb.nonNullable.group({...})
Builds the form. nonNullable makes reset() return fields to their initial value instead of null.
valid / touched / dirty / pending
Validators pass / focused-then-blurred / user changed it / async validator running.
When to show an error
invalid && touched. On submit, call markAllAsTouched() so every error appears at once.
Custom validator
A function returning null for valid, or { errorName: details } for invalid. Cross-field validators go on the group.
getRawValue() vs value
value omits disabled controls. getRawValue() includes them — usually what you want on submit.
(ngSubmit) not (click)
Submitting on the form element makes the Enter key work, which keyboard users rely on.
Signal Forms
Stable in Angular 22. form(modelSignal, schema) gives one source of truth instead of a form object plus a copy. Learn reactive forms first.

11 · ConfidenceTesting What You Built — Three Kinds, One Habit

Angular generates a test file beside every component and service. Testing a service is ordinary TypeScript testing; testing a component means rendering it and asking what the user would see.

Since Angular 21 the default test runner is Vitest, which replaced Karma. Vitest runs tests in Node with a simulated browser, which is why a test suite that took ninety seconds under Karma now takes a few.

terminalruns offline
ng test                 # runs every *.spec.ts, watches for changes
ng test --watch=false   # single run, for continuous integration

Testing a service — no framework needed

A signal-based service is a plain class. You can construct it directly, with no TestBed at all, and that is the fastest test you will ever write.

src/app/task.spec.tsruns offline
import { describe, it, expect } from 'vitest';
import { TaskService } from './task';

describe('TaskService', () => {
  it('starts empty', () => {
    const store = new TaskService();
    expect(store.tasks()).toEqual([]);
    expect(store.isEmpty()).toBe(true);
  });

  it('derives openCount from the list', () => {
    const store = new TaskService();
    store.add('write tests');
    store.add('ship it');

    expect(store.openCount()).toBe(2);

    store.toggle(store.tasks()[0].id);
    expect(store.openCount()).toBe(1);
    expect(store.doneCount()).toBe(1);
  });

  it('does not mutate the previous array', () => {
    const store = new TaskService();
    store.add('one');
    const before = store.tasks();
    store.add('two');

    // The old array is untouched -- this is what makes change detection work.
    expect(before.length).toBe(1);
    expect(store.tasks().length).toBe(2);
  });
});

Read the third test. It checks the replace-do-not-mutate discipline directly. If somebody later "optimises" add into a push, this test fails immediately — instead of a screen going stale in production two months later.

Testing a component — render it, then ask what the user sees

TestBed is Angular's test harness. It builds a miniature application containing just your component, with providers you choose.

src/app/task-list/task-list.spec.tsruns offline
import { describe, it, expect, beforeEach } from 'vitest';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { TaskList } from './task-list';
import { TaskService } from '../task';

describe('TaskList', () => {
  let fixture: ComponentFixture<TaskList>;
  let store: TaskService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [TaskList],          // standalone components go in imports
    }).compileComponents();

    fixture = TestBed.createComponent(TaskList);
    store = TestBed.inject(TaskService);
    fixture.detectChanges();        // run the first render
  });

  it('shows the empty message with no tasks', () => {
    const text = fixture.nativeElement.textContent;
    expect(text).toContain('Nothing yet');
  });

  it('renders one row per task', () => {
    store.add('first');
    store.add('second');
    fixture.detectChanges();        // re-render after the state change

    const rows = fixture.nativeElement.querySelectorAll('li');
    expect(rows.length).toBe(2);
    expect(rows[0].textContent).toContain('first');
  });
});

fixture.detectChanges() is the line everyone forgets. Outside a real application there is no render loop running, so a signal change updates the value but nothing redraws. The test then reads the old DOM and fails in a way that looks like a bug in your component.

Notice what these tests assert: the text on the screen and the number of rows. They do not reach into private fields or call internal methods.

That is the habit worth forming. Test what the user experiences, not how the component is built. A test that asserts on internals fails every time you refactor, which teaches the team to delete tests.

Testing something that fetches

http testing — no real networkruns offline
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [TaskPage],
    providers: [provideHttpClient(), provideHttpClientTesting()],
  }).compileComponents();
});

it('shows the tasks the server returned', async () => {
  const fixture = TestBed.createComponent(TaskPage);
  fixture.detectChanges();

  const http = TestBed.inject(HttpTestingController);
  const req = http.expectOne('/api/tasks?q=');    // asserts exactly one such request
  req.flush([{ id: 1, title: 'from the server', done: false }]);

  await fixture.whenStable();
  fixture.detectChanges();

  expect(fixture.nativeElement.textContent).toContain('from the server');
  http.verify();                                   // fails if any request went unanswered
});

expectOne asserts that your component asked for exactly that URL — so a typo in the endpoint fails the test rather than silently returning nothing. flush supplies the response. verify catches requests you did not expect.

What is worth testing, and what is not

Table 13 — Where test effort pays
Test thisWhySkip this
Service logic and computed derivations Cheap, fast, and it is where the business rules live That signal(0) starts at zero
What the component renders for each state Loading, error, empty and populated are four real screens users see That a private field has a particular name
Form validation rules They encode requirements, and requirements change That Angular's own Validators.required works
Guards, interceptors and route configuration Small functions with high blast radius when wrong Framework behaviour — the Angular team tests that

Quick reference — Testing

Runner
Vitest since Angular 21, replacing Karma. ng test watches; --watch=false for CI.
Services
A signal-based service is a plain class — construct it with new and assert on its signals. No TestBed needed.
TestBed
Builds a miniature app. Standalone components go in imports, not declarations.
fixture.detectChanges()
Renders. Required after every state change in a test, because there is no live render loop.
HttpTestingController
expectOne(url) asserts the request, flush(body) answers it, verify() fails on anything unexpected.
What to assert
Rendered text and element counts — what the user sees. Not private fields, which makes every refactor a test rewrite.

12 · Build itLab — The Task Board, End to End

One application that uses every idea in this chapter: components, signals, a service, routing, a form, and a fetch with all four states handled.

You have about eighty percent of this already, spread across the sections above. The lab is to assemble it and build the last twenty percent yourself.

LAB E14 — task-board, a complete small Angular application

Mission: build a task board with two routes. The list route shows tasks with a filter and a counter; the detail route shows one task by id. Data lives in a service and is persisted to localStorage so a refresh does not lose it.

Given to you (already written above): the Task interface, TaskService with its private signal and computed counts, TaskCard with input and outputs, TaskForm as a reactive form, and the routes table.

Build these six things:

  1. A filter that composes. Add searchText and showDone signals to the list component, and a visibleTasks computed that applies both to store.tasks(). The counter must show "showing 3 of 12" and stay correct with no code that updates it.
  2. Persistence with an effect. In TaskService, add an effect that writes the task array to localStorage whenever it changes, and a constructor that reads it back at startup. Handle the case where the stored JSON is corrupt.
  3. The detail route. Use withComponentInputBinding() and an id input. Show a "not found" message when no task has that id, rather than a blank screen.
  4. A canDeactivate guard on the form route that warns when the form is dirty and the user navigates away.
  5. Four states on a fetch. Replace the in-memory seed with an httpResource against any public JSON endpoint — or a local tasks.json file in public/. Render loading, error with a retry button, empty, and populated. Then break the URL on purpose and confirm the error state actually appears.
  6. Three tests. One that visibleTasks filters correctly; one that the list renders the empty message with no tasks; one that the detail component requests the right URL, using HttpTestingController.

Done when: ng test is green, ng build reports no errors, a refresh preserves your tasks, and breaking the API URL produces a visible error message rather than an empty list.

Stretch, if you want the senior version: lazy-load the detail route and confirm in the browser's network tab that its chunk downloads only on first visit. Then add @defer (on viewport) around a heavy component and watch the same thing happen on scroll.

13 · The canonThe Forty Questions Every Angular Screen Asks

These are the questions that decide a first or second Angular interview. Each answer is written to be said out loud, and each carries the follow-ups the interviewer reaches for next.

Say your answer before you open the panel. Committing to a wrong answer and then reading the right one is worth ten times reading the right one first — that gap is what your memory actually stores.

Canon · Framework, components and templates (Q1–14)

These test whether you understand the framework as a set of decisions rather than a set of commands you have typed.

Q1. "What problem does Angular solve that plain JavaScript does not?"

Reveal answer

The real test Whether you can name the actual job, rather than listing features you have used.

Strong answer The job is keeping the screen in agreement with the data. In plain JavaScript I have to find each element and update it by hand every time a value changes, and every place I forget is a stale screen.

Angular lets me declare the relationship once — this heading shows this value — and then guarantees it holds forever. I stop writing update code entirely.

On top of that one job, Angular adds the pieces a real application needs and versions them together: routing, forms, an HTTP client, dependency injection, a test harness and a build system. That is the difference between a framework and a rendering library.

Land it The trade is that I give up direct control of the page and get back the guarantee that the page is never wrong — which is worth it from about the fifth screen onward.

Likely follow-ups
"When would you not use Angular?"

For a mostly static marketing site, where the shipped JavaScript would outweigh the page it renders. A static site generator or plain HTML with a little JavaScript is faster to build and faster to load.

For a small widget embedded in someone else's page, where I need a tiny footprint and no opinions about routing or forms.

And for a team that is already fluent in something else and has no reason to switch — the framework is rarely the bottleneck, and a team's familiarity usually beats a framework's merits.

"Angular has a reputation for being heavy. Is that fair?"

It was fair, and it is much less so now. Standalone components removed the module ceremony, the built-in control flow removed the directive imports, and tree-shaking plus lazy routes mean an application ships what it uses rather than the whole framework.

The honest remaining cost is conceptual: dependency injection, RxJS in older code, and change detection are real things to learn before you are productive. That is a steeper first week than React's, and a flatter fifth month.

Q2. "What is a component, and what are its parts?"

Reveal answer

Strong answer A component is one piece of the screen, and it has four parts. A selector, which is the tag name other templates use to place it. A template, the HTML with bindings in it. A class, holding the data and the methods that change it. And styles, which are scoped to that component only.

The decorator @Component({...}) ties them together. It is a label carrying configuration — Angular reads it at build time and generates the rendering code.

An application is a tree of components. The root one is named in bootstrapApplication and rendered into the <app-root> tag in index.html.

Land it The useful way to think about it is a form template plus one filled-in copy: the template is the layout, the class instance is the data in the blanks.

Likely follow-ups
"What does 'standalone' mean?"

It means the component declares its own dependencies in an imports array, rather than being listed in a separate NgModule.

Before standalone, every component had to be declared in exactly one module, and using a component from another module meant exporting it there and importing that module here. Forgetting a step produced the most-searched error in Angular's history.

Standalone is the default since Angular 19, so you no longer write standalone: true — seeing it written explicitly tells you the codebase migrated but has not cleaned up.

"Why are component styles scoped, and how does Angular do it?"

Scoping stops a broad selector like p { color: red } in one component from repainting the whole application, which is what makes CSS in a large codebase survivable.

Angular does it by adding a generated attribute — something like _ngcontent-ng-c123 — to every element the component rendered, then rewriting your selectors to require that attribute.

The consequence is that a parent cannot style into a child. The escape hatch ::ng-deep works but leaks and is being phased out; the right answer is usually an input on the child or a CSS custom property, which passes through because it is an inherited value rather than a selector.

Q3. "Explain the four binding syntaxes and when each is used."

Reveal answer

Strong answer There are four, and the punctuation tells you the direction.

  • {{ value }} — interpolation. Class to screen, as text.
  • [property]="expr" — property binding. Class to screen, setting a DOM property such as disabled, src or value.
  • (event)="handler()" — event binding. Screen to class, running a method when something happens.
  • [(thing)]="value" — two-way binding, which is exactly the previous two combined.

Square brackets look like a box being filled from the class; parentheses look like a mouth shouting an event back. The two-way form is nicknamed banana in a box.

Land it The one to get right is property binding: bind to DOM properties, not HTML attributes, because attributes are the initial text and properties are the live state.

Likely follow-ups
"What is the difference between [disabled]="false" and disabled="{{false}}"?"

The first sets the DOM property disabled to the boolean false, so the button is enabled. That is correct.

The second sets the HTML attribute to the string "false". In HTML, boolean attributes work by presence — the mere existence of disabled disables the element regardless of its value — so the button is permanently dead.

This is one of the most common beginner bugs, and it generalises: interpolation into an attribute always produces a string, so never interpolate into a boolean attribute.

"Is there ever a reason to bind an attribute rather than a property?"

Yes, when there is no matching DOM property. ARIA attributes and SVG attributes are the common cases — there is no element.ariaLabel equivalent for every ARIA attribute, and SVG uses attributes throughout.

For those Angular has an explicit syntax: [attr.aria-label]="label()", [attr.colspan]="n()". Binding null to an attribute removes it entirely, which is the correct way to conditionally drop one.

Q4. "Why does @for require a track, and what goes wrong without a good one?"

Reveal answer

The real test Whether you understand that Angular is matching old rows against new ones, not just printing a list.

Strong answer On every render Angular has an old list of DOM rows and a new list of items, and it has to decide which old row corresponds to which new item. track is how I tell it — usually by a unique id from the data.

With a good track, reordering three items is three DOM moves. Without one, Angular cannot recognise anything, so it destroys every row and builds new ones.

The visible symptoms are specific: focus jumps out of an input mid-typing, checkbox state resets, scroll position is lost, CSS animations restart, and a hundred-row table re-renders to move one row.

I track by the index only when the list genuinely never reorders and the items have no other identity.

Land it Track by a stable unique identifier from the data — that is the difference between a list that moves rows and a list that rebuilds them.

Likely follow-ups
"What happens if two items have the same track value?"

Angular throws a runtime error saying the track expression produced duplicate keys, and names the value. It has to — two rows claiming the same identity make the matching ambiguous, and silently picking one would corrupt the list on the next update.

In practice this shows up when someone tracks by a field that is not actually unique, like a title or a date, or when a list is concatenated from two sources whose ids overlap. The fix is a genuinely unique key, or a composite one.

"How does this compare to React's key prop?"

It is the same idea with the same failure modes. React's key and Angular's track both give list items a stable identity so the framework can move nodes rather than rebuild them, and both degrade the same way when you use the array index on a reorderable list.

Two differences worth naming: Angular requires track and fails the build without it, whereas React only warns; and Angular's version is an expression rather than a prop, so it can be a composite like track item.type + item.id.

Q5. "Why should you not call a method from a template?"

Reveal answer

Strong answer Because a template expression is re-evaluated on every render, and a method call has no caching and no dependency tracking. Angular has no way to know whether the result could have changed, so it must call it again.

If the method filters or sorts a list, that work runs on every render, including renders triggered by something unrelated on the page. Under the old Zone.js model that could be dozens of times a second during a scroll.

The fix is a computed. It is lazy — it does not run until something reads it — and it is cached until its dependencies actually change. The same filter then runs once per real data change instead of once per render.

Land it Anything a template needs repeatedly should be a signal or a computed, so the cost is paid per change rather than per render.

Likely follow-ups
"Is it ever fine to call a method in a template?"

Yes, in event bindings — (click)="save()" runs once when clicked, not on every render, and that is exactly what it is for.

It is also fine for a genuinely trivial pure function that takes no measurable time, though I would still prefer a computed for consistency, because the next person will not check whether it is cheap.

What is never fine is a method that has a side effect, or one that returns a new object or array each call. Returning a fresh array on every call defeats every identity check downstream and can produce infinite re-render loops.

"How would you notice this problem in a running application?"

I would put a console.count() in the suspicious method and interact with an unrelated part of the page. If the count climbs while nothing relevant changed, that is the bug.

More systematically, Angular DevTools has a profiler that shows change detection cycles and how long each component took. A component that is expensive on cycles it should not care about points straight at a method call or a missing OnPush.

Q6. "What replaced *ngIf and *ngFor, and why did Angular change it?"

Reveal answer

Strong answer Built-in control flow — @if, @for, @switch — since Angular 17. It is real template syntax rather than directives, so it needs no imports at all.

Three reasons for the change. It removed the CommonModule import that every standalone component otherwise needed. It made the else branch readable — the old form needed a separate named ng-template, which the new @else replaces. And because the compiler understands it directly, it generates smaller and faster code.

The asterisk in *ngIf was always shorthand for wrapping the element in an invisible <ng-template>, which is why the old syntax was awkward in exactly those places.

Land it The old form still works and is everywhere in existing code, and ng generate @angular/core:control-flow migrates a whole project automatically.

Likely follow-ups
"Are structural directives gone entirely?"

No. The three built-in ones are superseded, but the mechanism remains and custom structural directives still work — anything you write yourself with TemplateRef and ViewContainerRef, such as a *hasPermission directive.

What changed is that the common cases are now syntax the compiler knows about, so they are faster and need no import, while the extension point is still there for the uncommon ones.

"What is @defer?"

It is control flow for loading rather than for showing. @defer wraps a chunk of template and does not download that component's code until a trigger fires — on viewport, on interaction, on idle, on hover, or a timer.

It has companion blocks: @placeholder for before the trigger, @loading for while the chunk downloads, and @error for when it fails.

It is the easiest real performance win in modern Angular, because it moves heavy things below the fold — charts, editors, maps — out of the initial bundle with about four lines of template.

Q7. "What is the difference between an interface and a class in TypeScript, and which do you use for API data?"

Reveal answer

Strong answer An interface is a compile-time description of a shape. It is erased entirely when the code is compiled, so it costs nothing at runtime and cannot be instantiated.

A class is a real runtime thing: it produces a constructor function, it can hold methods and private state, and it exists in the shipped JavaScript.

For data coming from an API I use an interface. The JSON that arrives is a plain object, not an instance of anything, so a class would be a lie — instanceof would be false and any methods I declared would not exist on the parsed object.

Land it Interface for shapes, class when you need behaviour or identity at runtime; API responses are always shapes.

Likely follow-ups
"Does http.get<Task>() validate that the response is really a Task?"

No. The generic is a claim to the compiler, not a runtime check. Angular parses the JSON and hands it back; if the server sent a different shape, nothing complains at that moment.

The failure surfaces later and further away — a property is undefined three components downstream, and the stack trace points at the innocent component rather than the API.

If the API is not mine, or the contract is unstable, I validate at the boundary with something like Zod or a hand-written type guard, so a bad response fails loudly at the edge with a useful message.

"What is the difference between interface and type?"

For describing an object shape they are almost interchangeable. Two differences matter in practice.

interface supports declaration merging — declaring it twice combines the members — which is how library type augmentation works, and which is also a hazard if you do it by accident.

type can express things interface cannot: unions, intersections, mapped and conditional types, and aliases for primitives. So the working convention is interface for object shapes and type for everything else.

Q8. "What does <ng-content> do, and when would you use it instead of an input?"

Reveal answer

Strong answer <ng-content> is content projection: it marks the place where markup written by the caller gets inserted. An input passes data; projection passes markup.

I reach for projection when the component owns the structure but not the contents — a card, a dialog, a panel, a tab. The component decides the border, padding and header layout; each caller decides what goes inside.

Multiple slots work with a selector: <ng-content select="[panel-title]" /> takes children carrying that attribute, and a plain <ng-content /> catches everything else.

Land it If I find myself adding a fifth input just to describe what should be rendered inside, that is the signal to project markup instead.

Likely follow-ups
"When is projected content created — by the parent or the child?"

By the parent. The projected nodes are created in the parent's context and then moved into the child's view, which has two consequences people trip over.

First, expressions inside projected content resolve against the parent's class, not the child's — so you cannot read the child's fields there.

Second, projected content is created even if the child never renders the <ng-content>. If you wrap it in an @if that is false, the content is still constructed, just not attached. For expensive content, take an ng-template and render it with ngTemplateOutlet instead, which really is lazy.

Q9 · Scenario. "A junior on your team writes <app-card task="selectedTask" /> and the card shows nothing. What happened?"

Reveal answer

Strong answer The square brackets are missing. Without them, Angular passes the literal string "selectedTask" rather than evaluating it as an expression.

With a typed input.required<Task>() this is caught at build time, because a string is not assignable to Task. That is a good outcome — the error names the exact line.

If the input's type happened to be string, or the project has strict template checking turned off, it compiles and the card renders the word "selectedTask" or nothing at all, which is much harder to spot.

Land it Brackets mean "evaluate this"; no brackets means "this literal text" — and keeping strictTemplates on is what turns that from a silent bug into a build error.

Likely follow-ups
"When would you deliberately pass a static string with no brackets?"

Whenever the value really is a constant — <app-badge variant="danger" /> or <app-icon name="trash" />. It is shorter and it reads better than [variant]="'danger'".

The one to watch is booleans: <app-x disabled="false" /> passes the string "false", which is truthy. Either use brackets, or declare the input with transform: booleanAttribute so presence-based flags behave like native HTML.

"What is strictTemplates?"

A TypeScript compiler option Angular adds, on by default in new projects, that type-checks template expressions the same way it checks your TypeScript.

With it on, binding a string to a Task input, calling a method that does not exist, or reading a property that is possibly undefined all fail the build. With it off, templates are effectively untyped and those become runtime surprises.

Turning it off to make a migration compile is a common and expensive shortcut — it disables the checking on every template in the project, not just the awkward ones.

Q10. "What is the difference between @Input() and the new input()?"

Reveal answer

Strong answer They do the same job — receive a value from the parent — but input() returns a signal, and that changes what you can do with it.

With @Input(), reacting to a change meant implementing ngOnChanges and picking the field out of a string-keyed SimpleChanges object, comparing previous and current values by hand.

With input(), I write a computed that reads it, and the derived value is simply always correct. No lifecycle hook, no comparison, no string keys.

input.required<T>() also gets me build-time enforcement, where the old form needed a non-null assertion and a hope.

Land it The pattern across all the new APIs is the same: lifecycle hooks are being replaced by reactivity, so instead of being told to go and look, you declare a relationship that stays true.

Likely follow-ups
"Can you mix both styles in one component?"

Yes, and during a migration you will. A component can have some @Input() fields and some input() signals, and the parent's template looks identical either way.

The one thing to be careful about is ngOnChanges: it fires for decorator inputs but not for signal inputs, so a component that is half-migrated can have a hook that quietly stops covering some of its inputs. That is worth grepping for when you convert a component.

"Are signal inputs writable inside the child?"

No. input() returns a read-only signal, deliberately — the parent owns the value, so letting the child write it would break unidirectional data flow and reintroduce the "who changed this?" problem.

If the child genuinely needs to own an editable copy that resets when the parent's value changes, that is linkedSignal. If the parent and child should share one editable value, that is model(), which is two-way by design.

Q11. "Explain unidirectional data flow and why Angular enforces it."

Reveal answer

Strong answer Data flows down through inputs and events flow up through outputs. A child never writes the state it was given; it reports that something happened and the owner decides what to do.

The reason is debuggability. If any component can mutate any object it receives, then a wrong value could have been written in forty places and finding it means searching the tree.

With one writer per piece of state, a wrong value has exactly one function that could have produced it. Debugging becomes reading that function.

It is the same reasoning as having a single writer per row in a database, or a single source of truth in any system.

Land it The rule costs a little ceremony per component and saves an unbounded amount of searching later, which is why it is the default rather than an option.

Likely follow-ups
"What is ExpressionChangedAfterItHasBeenCheckedError and how does it relate?"

It is Angular telling you that a binding's value changed after it had already been rendered in the same cycle — usually because a child wrote to something the parent had already displayed.

That is precisely a unidirectional-flow violation: information travelled back up and changed an answer that had already been given. Angular only raises it in development mode, where it runs a second verification pass.

The usual causes are writing to a parent's state inside ngAfterViewInit, or a getter in a template that returns a new object each call. The fix is to move the write into an event handler, or to derive the value with computed so there is nothing to write.

"How do two sibling components share state, then?"

They do not talk to each other. The state moves up to the nearest common ancestor, or out into a service, and both siblings read from there.

For a couple of components a shared parent is enough. For anything wider I put it in a service with providedIn: 'root', holding a private signal and exposing asReadonly() plus methods — so both siblings see the same values and neither can write them directly.

Q12. "What are the main lifecycle hooks, and which ones still matter?"

Reveal answer

Strong answer The ones worth knowing are ngOnInit, which runs once after the first inputs are set; ngOnChanges, which runs whenever a decorator input changes; ngAfterViewInit, which runs once the component's own template exists in the DOM; and ngOnDestroy, which runs on teardown.

In modern Angular most of them have shrunk in importance. ngOnChanges is replaced by computed over signal inputs. ngOnInit is often unnecessary, because field initialisers and resources cover the same ground.

The two that still earn their place are ngAfterViewInit, for cases where you genuinely need a real DOM element — measuring, focusing, handing a node to a charting library — and ngOnDestroy, for cleaning up anything Angular did not create.

Land it The direction of travel is from hooks to reactivity: prefer a derivation that is always true over a callback that tells you to go and update something.

Likely follow-ups
"Why is ngOnInit separate from the constructor?"

Because when the constructor runs, inputs have not been set yet. Angular constructs the class first and then assigns the input values, so anything in a constructor that reads an input sees undefined.

The convention that follows is: constructors do dependency injection and nothing else; work that depends on inputs goes in ngOnInit or, better, in a computed that reads the input signal and therefore has no ordering problem at all.

"What replaces ngOnDestroy for cleanup now?"

Two things, depending on what you are cleaning up. takeUntilDestroyed() ends an RxJS subscription when the component is destroyed, and it can be written inline at the point of subscription instead of in a distant hook.

DestroyRef with inject(DestroyRef).onDestroy(fn) registers arbitrary cleanup from anywhere in an injection context, which is useful in services and functions where there is no component hook available.

Effects and resources clean themselves up automatically, so a lot of what used to live in ngOnDestroy now has no code at all.

Q13. "What is a pipe, and when would you write one?"

Reveal answer

Strong answer A pipe transforms a value for display, written with a vertical bar in the template: {{ amount | currency:'INR' }}. Angular ships several — date, currency, number, percent, json, async, titlecase.

I write one when the same formatting appears in several templates and it genuinely is presentation, not logic. A pipe for rendering a duration as "3h 20m" is reasonable.

Pipes are pure by default, which means Angular caches the result and only recomputes when the input reference changes. That is what makes them cheaper than a method call in a template.

Land it Pipes are for formatting; filtering and sorting belong in a computed, which is why Angular deliberately ships no filter or orderBy pipe.

Likely follow-ups
"Why does Angular not ship a filter pipe, when AngularJS did?"

Two reasons the team gave, and both hold up. Performance: a filter pipe runs inside change detection on a list that could be large, and making it impure to catch mutations means running it on every cycle.

And minification: the original AngularJS filter took an expression string, which cannot be tree-shaken or type-checked, so it hid errors and bloated the bundle.

The replacement is to filter in the class with a computed, which is typed, cached, testable without rendering anything, and runs once per data change rather than once per render.

"What is an impure pipe and when is one justified?"

An impure pipe — @Pipe({ name: 'x', pure: false }) — re-runs on every change detection cycle instead of only when its input reference changes. That is expensive and usually the wrong tool.

The legitimate case is a pipe whose output depends on something outside its arguments, such as the async pipe, which must react when the observable emits rather than when its input changes.

If I am tempted to make a pipe impure to catch a mutated array, the real fix is to stop mutating the array — which is the same discipline signals require anyway.

Q14. "How do you get a reference to a real DOM element, and when is that acceptable?"

Reveal answer

Strong answer I put a template reference variable on the element — <input #search> — and read it with viewChild, which gives me a signal that is populated once the view exists.

It is acceptable for the handful of things that are genuinely about the DOM and cannot be expressed as data: moving focus, measuring an element's size, scrolling to a position, or handing a node to a third-party library like a chart or a map.

It is not acceptable for changing what is displayed. Setting textContent or toggling a class by hand puts the DOM and the framework's model out of step, and the next render silently overwrites it.

Land it Reach for the DOM to do things the DOM alone can do; express everything else as state and let Angular render it.

Likely follow-ups
"What is the difference between viewChild and contentChild?"

viewChild looks inside the component's own template — things the component itself rendered.

contentChild looks at what was projected into it by a caller through <ng-content>. A tab-group component uses contentChildren to find the tabs the caller wrote inside it.

They also differ in timing: view children are ready after the component's view is created, content children after the projected content is — which under the old decorators meant two different lifecycle hooks, and with signal queries means neither, since you just read the signal when it has a value.

"Why do people say not to use ElementRef.nativeElement directly?"

Mostly for server-side rendering. Code running on the server has no document and no real elements, so anything touching nativeElement at construction time throws there and works locally, which is a nasty class of bug.

There is also a security angle: writing innerHTML from a nativeElement bypasses Angular's sanitisation and is a straightforward cross-site-scripting hole.

The safe pattern is to do DOM work only in afterNextRender or ngAfterViewInit, which do not run on the server, and to bind values rather than write markup.

Canon · Signals, services and dependency injection (Q15–27)

This block is where modern Angular interviews spend most of their time, because it is the part that changed most recently and the part that separates people who read the docs from people who read a tutorial.

Q15. "What is a signal, and why did Angular add them?"

Reveal answer

The real test Whether you can state the problem signals solve, not just the API.

Strong answer A signal is a value in a box that keeps track of who read it and notifies them when it changes. You read it by calling it: count().

The problem it solves is that a plain field cannot tell anyone it changed. When I write this.count = 5, JavaScript assigns a number and notifies nobody, so the framework has no way to know.

Angular's old answer was Zone.js, which patched every browser API — timers, event listeners, network calls — so that after anything asynchronous finished it could say "something may have changed" and re-check every binding in the entire component tree.

Signals replace that guess with a fact. Because Angular knows exactly which templates read which signal, one change marks two components dirty instead of forty.

Land it Zone.js knew that something happened; a signal knows what happened and who cares — that is the whole performance story.

Likely follow-ups
"Why do you have to call a signal instead of just reading a property?"

Because the call is what registers the dependency. When Angular renders a template it sets a flag saying "I am the current consumer"; a signal read while that flag is set records the reader.

A plain property read is invisible to any framework — there is no hook on it. A getter could work in principle, but a function call makes the cost and the tracking explicit at the call site, which the team judged to be clearer.

The practical consequence is the first bug everyone writes: {{ count }} without parentheses prints the function itself rather than the value.

"Do signals replace RxJS?"

No, they overlap in one area and not the rest. Signals model state: a current value that always exists and that you can read synchronously.

RxJS models streams of events over time: things that happen zero or many times, that may never produce a value, and that need operators like debounce, retry, combine and cancel.

So signals have taken over component state, where an observable with a BehaviorSubject was always slightly the wrong shape. RxJS keeps typing, WebSockets, complex request coordination and anything where time and cancellation are the problem. toSignal and rxResource exist to move between the two.

Q16. "What is the difference between signal, computed and effect?"

Reveal answer

Strong answer signal is a writable source of truth, with set and update. It is for state somebody edits — a filter, a loaded list, a form value.

computed is a read-only value derived from other signals. It is lazy, so the function does not run until something reads it, and cached, so it does not run again until a dependency actually changes.

effect produces no value at all. It re-runs a side effect when its dependencies change, and it exists for reaching outside Angular — writing to localStorage, logging, syncing a third-party library.

The rule I apply: if a value can be calculated from other values, it is a computed, never a second signal I keep in step by hand.

Land it The moment you write code that updates signal B whenever signal A changes, you have written a computed the hard way — and created a line somebody can forget.

Likely follow-ups
"Why is it bad to write to a signal inside an effect?"

Three reasons. It is almost always a computed in disguise, so it is more code for the same result. It runs later than a computed would, so there is a window where the derived value is stale. And it can loop, if the effect reads something its own write invalidates.

Angular pushes back on it deliberately: writing to a signal in an effect warns, and there is an explicit allowSignalWrites-style escape for the rare legitimate case.

The genuinely legitimate case — a writable value that resets when a source changes — has its own primitive now, linkedSignal, which is why the escape hatch is needed even less than it was.

"If a computed's dependencies change but nothing reads it, does it run?"

No. It marks itself stale, which is a flag flip, and does nothing else. The function runs on the next read, and only if a dependency genuinely changed value.

That laziness is why deriving expensive things with computed is cheap — a reduce over fifty thousand items on a tab nobody has opened costs nothing — and it is the exact opposite of calling a method from a template, which has no laziness and no cache.

Q17 · Scenario. "You push an item into an array held by a signal and the screen does not update. Why?"

Reveal answer

Strong answer Because signals compare the old and new value with Object.is, and for an array that compares identity, not contents.

this.tasks().push(item) reaches through the signal, gets the array, and mutates it in place. The signal still holds the same array object, so as far as it is concerned nothing was ever set and there is nothing to notify.

The fix is to replace rather than mutate: this.tasks.update(list => [...list, item]) creates a new array, which is a new identity, which fires the notification.

The same rule applies to objects — { ...task, done: true } rather than task.done = true.

Land it Replace, do not mutate. It costs a spread operator and removes an entire category of stale-screen bugs.

Likely follow-ups
"Isn't copying the array on every change expensive for a large list?"

Less than people expect, because it is a shallow copy: a new array of the same references, not a deep clone of every item. For ten thousand items that is copying ten thousand pointers, which is microseconds.

It is also what makes the rendering fast. Because unchanged items keep their identity, @for with a proper track recognises them and leaves their DOM alone — so you copy an array of pointers and avoid re-rendering rows.

If profiling ever showed it mattered, the answers would be an immutable data structure library with structural sharing, or splitting the list into several signals. I have never needed either in application code.

"Can you change the equality check?"

Yes. signal(value, { equal: myComparator }) and computed(fn, { equal: … }) both take a custom equality function, and Angular calls it to decide whether anything actually changed.

The useful case is a computed that rebuilds an object each time but is semantically unchanged — a custom deep comparison stops downstream consumers re-rendering for nothing.

It is a sharp tool: an equality function that says "equal" when the value really did change produces a silently stale screen, which is much harder to diagnose than the mutation bug it was meant to fix.

Q18. "What is linkedSignal for?"

Reveal answer

Strong answer For a value the user can edit that should also reset when something else changes — the case computed cannot cover because a computed is read-only.

The canonical example is a quantity selector on a product page. The user types 5, so it must be writable. Then they switch to a different product, and it should go back to 1.

linkedSignal(() => { this.selectedProduct(); return 1; }) does both: it is writable like a signal, and it recomputes from its source whenever the source changes.

Before it existed, this needed an effect that wrote to a signal — exactly the pattern Angular tells you to avoid.

Land it Whenever you catch yourself writing an effect whose only job is to reset a field, that is linkedSignal.

Likely follow-ups
"Give another real example."

A selected row in a table with a filter. The user clicks row 7 so the selection is writable; then they change the filter and row 7 is no longer in the list, so the selection should clear rather than point at something invisible.

Another is a paginator's current page: writable when the user pages, reset to 1 when the search term changes. Both are the same shape — user-owned, but invalidated by an upstream change.

Q19. "What is dependency injection and why does Angular use it?"

Reveal answer

Strong answer Dependency injection means a class asks for what it needs instead of constructing it. In Angular I call inject(TaskService) and the framework hands me the instance.

Angular keeps a chain of injectors — registries of how to build things — and searches from the component upward to the root, stopping at the first one that knows the token.

It buys three concrete things. Tests can substitute a fake with one provider line, because there is a seam. Lifetime becomes a configuration decision — moving a service from root to a route's providers changes it from app-lifetime to feature-lifetime with no code change. And configuration can be late-bound, so the same component runs against a real API or a stub depending on app.config.ts.

Land it Without DI you can still share a singleton by exporting an object — what you lose is the seam, and the seam is what makes the code testable and reconfigurable.

Likely follow-ups
"What does providedIn: 'root' actually do?"

It registers the class with the root injector, so the whole application shares one instance, created lazily on first injection.

The important second effect is tree-shaking. Because the registration lives on the class rather than in a module's providers array, a bundler can prove that a service nobody injects is unreachable and drop it from the bundle. With the old module-based registration it could not, so unused services shipped.

"What is NG0201 and how do you fix it?"

It means "No provider for X" — the injector search reached the root and found nothing that knows how to build the token.

The three usual causes: the service has no @Injectable({ providedIn: 'root' }); a provideSomething() call is missing from app.config.ts, which is what happens with HttpClient; or you are injecting a token that is provided on a route or component you are not actually inside.

In tests the cause is nearly always that TestBed.configureTestingModule did not include the provider, since the test injector starts empty rather than inheriting the app's.

Q20 · Scenario. "Two panels on the same screen show different task counts. Both inject the same service. What went wrong?"

Reveal answer

The real test Whether you know that where a service is provided decides how many instances exist.

Strong answer The service is almost certainly listed in a component's providers array rather than being providedIn: 'root'.

A component-level provider creates one instance per instance of that component. So each panel got its own store, each holding its own tasks, and neither can see the other's.

I would confirm it by injecting the service in both and logging identity — if storeA === storeB is false, that is the whole answer.

The fix is to provide it once, either with providedIn: 'root' or in the providers of the nearest common ancestor if the state should reset when that ancestor is destroyed.

Land it "Which injector provides it" is the same question as "how many copies exist and when do they die" — and putting a shared store on a component that renders in a loop is the classic way to get twenty stores holding a twentieth of the truth each.

Likely follow-ups
"When would a per-component service actually be what you want?"

When the state belongs to one screen and must reset when you leave it — a multi-step wizard's progress, a chart's zoom level, an editing draft.

Providing it on the component means it is created with the component and destroyed with it, so navigating away and back gives you a clean slate with no reset code of your own.

Providing it on a route is the middle ground: several sibling screens under one feature share one instance, and it dies when the user leaves the feature.

"How do you make it impossible for a component to corrupt shared state?"

Keep the writable signal private and expose asReadonly(), with public methods as the only way to change anything.

Components can read every value and call add, toggle or remove, but there is no set on the handle they hold, so a bad value has three functions it could have come from rather than forty components.

It costs one extra line per store and it is the highest-value habit in signal-based Angular.

Q21. "What is an InjectionToken and when do you need one?"

Reveal answer

Strong answer A token is the lookup key the injector uses. A class can be its own key, because a class is a unique runtime object. An interface cannot — interfaces are erased at compile time, so there is nothing left to look up by.

So for anything that is not a class — a configuration object, a base URL string, a feature-flag map, a factory function — I create new InjectionToken<ApiConfig>('API_CONFIG') and provide it with useValue.

The generic carries the type through, so inject(API_CONFIG) comes back typed as ApiConfig with no casting. The string argument is only for error messages.

Land it Class for services, token for values — and the token's identity, not its string, is what the injector matches on.

Likely follow-ups
"What are the four provider recipes?"

useClass builds a class when a token is asked for, which is how you swap a real implementation for a fake. useValue hands back an object as-is, for configuration and constants.

useFactory runs a function and returns its result, for values that depend on the environment or on other services — the factory can itself use inject().

useExisting is an alias: it returns whatever another token returns, which lets one service be exposed under a narrower interface without creating a second instance.

"What is a multi-provider?"

A provider with multi: true contributes to an array rather than replacing what is there. Several registrations for the same token all land in one array, and injecting it gives you all of them.

That is how extension points work — HTTP interceptors were built this way before the functional form, and validators and initialisers use the same pattern. It is the mechanism to reach for when you want "everyone who cares can add one".

Canon · Data, routing, forms and testing (Q22–40)

The second half of a screening interview is usually "show me you have shipped something": fetching with all its states, navigating, validating input, and proving it works.

Q22. "What is an Observable, and how is it different from a Promise?"

Reveal answer

Strong answer A promise is a single future value, and it starts working the moment you create it. An observable is a recipe for producing values over time, and it does nothing at all until something subscribes.

Two differences follow from that. An observable is lazy: calling http.get(...) sends no request; the request goes out on subscribe. And it can produce many values, or none, which is why it has cancellation and operators that a promise does not.

An HTTP observable happens to emit once and complete, so it behaves like a promise in practice — but the type does not know that, which is what makes retry, timeout and cancel-on-new-input possible.

Land it Promise for one value that is already on its way; observable for a stream you want to shape, retry or cancel.

Likely follow-ups
"When do you have to unsubscribe?"

When the observable never completes. Router events, fromEvent listeners, interval timers, WebSocket streams and valueChanges on a form all keep emitting, and a subscription that outlives its component keeps that component in memory — the classic Angular leak.

HTTP calls complete after one value, so they release themselves and need no cleanup.

The modern tool is takeUntilDestroyed() in the pipe, which ends the subscription when the injection context is destroyed and can be written right where you subscribe. toSignal and the async pipe handle it for you.

"What does it mean that an observable is cold?"

A cold observable creates its work per subscriber. Subscribe twice to http.get('/api/tasks') and two HTTP requests go out, because the recipe runs again from the start.

A hot observable shares one source among subscribers — a Subject, or a cold one wrapped in shareReplay.

This catches people out with the async pipe: using it twice on the same observable in one template fires two requests. The fix is one subscription — toSignal, an @if (…; as x) block, or shareReplay(1).

Q23. "How do you fetch data in modern Angular?"

Reveal answer

Strong answer For reads, httpResource. I give it a function that builds a URL, and I get back signals: value, isLoading, error and status, plus a reload() method.

If the URL function reads another signal — a filter, a route parameter — then changing that signal re-fetches automatically, and Angular cancels the previous request if it is still in flight. There is no code connecting the two; the dependency is the wiring.

For writes I inject HttpClient and subscribe once, because a POST happens at a moment I choose rather than as part of a dependency graph.

Both need provideHttpClient() in app.config.ts; without it you get NG0201.

Land it Resources for reading, HttpClient for writing — and the resource's real value is that loading and error states stop being flags you set in two places and forget in a third.

Likely follow-ups
"What are the states a data screen must handle?"

Four. Loading, error, empty-but-successful, and populated.

The one that gets skipped is the difference between error and empty, and that is the most common defect I see in production frontends: the request failed, the list is empty, and the screen says "no tasks". The user concludes their data is gone.

A resource gives a distinct signal for each, so the template has an @if per state and a retry button on the error branch. I would also say out loud that the error message should not print the raw exception — it should say what to do next.

"How would you debounce a search box that drives a resource?"

Angular 22 has debounced(signal, ms), which returns a signal that lags the source. I would read that inside the resource's URL function, so the request only follows the settled value.

Without it, the pattern is a toSignal over the input's valueChanges piped through debounceTime, or an rxResource whose source stream is debounced.

Worth adding: even undebounced, a resource cancels the previous request when its inputs change, so out-of-order responses cannot overwrite newer ones. Debouncing saves requests; cancellation is what saves correctness.

Q24. "What is an HTTP interceptor and what would you put in one?"

Reveal answer

Strong answer An interceptor is a function every HTTP request passes through on the way out and every response passes through on the way back. They are registered with provideHttpClient(withInterceptors([...])).

I put cross-cutting concerns there: attaching an authentication header, adding a correlation id for tracing, logging slow requests, showing a global loading bar, and handling 401 by logging the user out.

Requests are immutable, so an interceptor calls req.clone({ setHeaders: … }) and passes the copy on. That is deliberate — it means a retry re-sends the request as originally made rather than one that has been edited mid-flight.

Land it Anything every call must do belongs in an interceptor, so that no individual call has to remember it — the same reasoning as a servlet filter chain on the server.

Likely follow-ups
"In what order do multiple interceptors run?"

In array order on the way out, and in reverse on the way back — the same nesting as middleware. The first one listed is the outermost, so it sees the request first and the response last.

That matters for pairs: a logging interceptor placed first measures the full time including everything the others do, while placed last it measures only the network.

"How would you implement token refresh in an interceptor without a stampede?"

Catch the 401, then refresh once and replay the failed request with the new token. The trap is that ten parallel requests all get 401 and all try to refresh, so you get ten refresh calls and usually nine invalidated tokens.

The standard fix is a shared in-flight refresh: hold the refresh observable in the service, have every 401 subscribe to that same one, and clear it when it settles — shareReplay(1) over a single subject.

I would also guard against looping: if the refresh call itself returns 401, log out rather than retrying, or a bad refresh token produces an infinite cycle.

Q25. "How does the Angular router decide which component to show?"

Reveal answer

Strong answer It walks the routes array from the top and takes the first path that matches the URL — not the most specific one. Order is the algorithm.

The matched component is rendered into <router-outlet />, replacing whatever was there. Child routes render into nested outlets.

Two consequences follow. The wildcard '**' must be last, or it swallows everything below it. And redirectTo usually needs pathMatch: 'full', otherwise an empty-path redirect matches the prefix of every URL and you get a redirect loop.

Land it First match wins, top to bottom — so a routes array is a priority list, not a set.

Likely follow-ups
"How do you read a route parameter?"

The modern way is withComponentInputBinding() in provideRouter, after which :id in the path arrives as an input() named id on the component. Query parameters bind the same way.

Because inputs are signals, navigating from /tasks/42 to /tasks/99 just works: the router reuses the component, the input changes, and anything derived from it recomputes.

The old approach was ActivatedRoute.snapshot.params, and its famous bug is exactly that navigation — the snapshot was read once in the constructor, the component was reused rather than recreated, and the page kept showing task 42 forever. The observable form, route.params.subscribe, avoided it but needed manual cleanup.

"Why is routerLink better than href?"

href is a full page navigation: the browser discards the running application and downloads it again. Every signal, every service instance and every bit of in-memory state is lost, and the user waits for a cold start.

routerLink updates the address bar with the History API and swaps components in place, which is instant.

The one time href is right is leaving your application — an external site, or a server-rendered download endpoint.

Q26. "What is lazy loading and how much does it actually help?"

Reveal answer

Strong answer Lazy loading means a route's component is fetched only when someone first visits it. You write loadComponent: () => import('./x').then(m => m.X), and the build tool sees the dynamic import and emits a separate file.

The help is proportional to how much of your app most users never open. In a typical product with a customer area and an admin area of similar size, splitting takes the initial download from roughly 900 KB to 450 KB.

On a slow mobile connection that is a couple of seconds off first render, which is the number users judge you on and the number Core Web Vitals measures.

My rule is that every top-level feature area gets its own lazy route, from the first day rather than as a later optimisation.

Land it The cost is one arrow function per route; the benefit compounds with every feature the team adds after you.

Likely follow-ups
"Doesn't that make the first click on a lazy route slow?"

It can, and the answer is preloading. provideRouter(routes, withPreloading(PreloadAllModules)) downloads lazy chunks in the background after the first page is interactive, so the initial render stays small but the later navigation is instant.

For a large app, a custom preloading strategy is better than all-or-nothing: mark the two or three routes users actually go to next with data: { preload: true } and preload only those.

Angular 22 also has injectAsync with a prefetch: onIdle(...) option for the same idea at the service level.

"How is @defer different from a lazy route?"

A lazy route splits on navigation; @defer splits inside a page that is already open. It wraps part of a template and downloads that code when a trigger fires — on viewport, on interaction, on idle, on hover, or a timer.

It is the right tool for heavy things below the fold: a chart library, a rich text editor, a map. Those often dominate a bundle while being irrelevant to most visits.

It also has @placeholder, @loading and @error blocks, so the four states are handled in the template rather than by hand.

Q27. "What is a route guard, and is it a security feature?"

Reveal answer

The real test Whether you say "no" to the second half without hesitating.

Strong answer A guard is a function the router runs before activating a route. It returns true to allow, false to block, or a UrlTree to redirect — typically to a login page carrying a returnUrl.

It is not a security feature. It runs in the browser, in JavaScript the user can read, edit or simply skip by calling the API directly with any HTTP client.

Its real job is user experience: it stops a legitimate user from landing on a screen that would show them nothing but errors.

Every guard must be matched by an authorisation check on the server, on every endpoint, and the server's answer is the one that counts.

Land it A guard hides a door; the server locks it — and only one of those stops an attacker.

Likely follow-ups
"What is canDeactivate for?"

Asking a component whether it is willing to be left — the "you have unsaved changes" prompt. The guard receives the component instance, so it can ask form.dirty and return a confirmation.

The honest limitation: it only covers navigation inside the application. Closing the tab or typing a new URL bypasses the router entirely, so a complete implementation also listens for the browser's beforeunload event.

"How would you protect a lazy-loaded admin area properly?"

Three layers. A canMatch guard on the route, which is better than canActivate here because it prevents the chunk from even being downloaded, so the admin code is not sitting in a non-admin's browser.

Server-side authorisation on every admin endpoint, checked from a token the server validates rather than anything the client sends about itself.

And no secrets in the frontend bundle at all — a JavaScript file is public, whatever route it sits behind.

Q28. "Reactive forms or template-driven — which do you use and why?"

Reveal answer

Strong answer Reactive, for anything real. The form's structure is defined in TypeScript, so it is typed, testable without rendering, and easy to build dynamically.

Template-driven forms put the structure in the HTML with [(ngModel)]. They are quicker for a two-field filter bar, but cross-field validation is awkward, testing means rendering, and there is no typed object to hand to a service.

As of Angular 22 there is a third: Signal Forms, where the model is a signal and the form is a view over it, so there is one source of truth instead of a form object plus a copy of the data.

I would learn reactive forms first regardless, because that is what is in every existing codebase and every interview.

Land it Reactive is the default; template-driven for trivial cases; Signal Forms for new code on 22, with compatForm() to migrate one form at a time.

Likely follow-ups
"When should a validation error become visible?"

On invalid && touched, not on invalid alone. A required field is invalid the instant the form appears, so showing that error immediately tells the user off for not having typed yet.

Touched means focused and then blurred, so the error appears when they leave the field — which reads as help rather than as scolding.

On submit I call markAllAsTouched() so every problem appears at once, instead of the user fixing one error and discovering another.

"What is the difference between value and getRawValue()?"

value omits disabled controls. That surprises people at submit time: a field disabled because it is derived or read-only silently disappears from the payload, and the server sees a missing field rather than the value on screen.

getRawValue() includes everything, and with nonNullable groups it is fully typed. It is what I use on submit unless I specifically want disabled fields excluded.

Canon · Change detection, quality and shipping (Q29–40)

The last block is what separates "I have built screens" from "I have kept an application alive". Interviewers use these to find out whether you have ever had to make a page faster or a bug reproducible.

Q29. "What is change detection, and what does OnPush do?"

Reveal answer

Strong answer Change detection is the pass where Angular walks the component tree, re-evaluates each binding, and updates the DOM where a value differs from last time.

The default strategy checks every component on every pass. OnPush tells Angular it may skip a component unless one of four things happened: one of its inputs changed by reference, an event fired inside it, something explicitly marked it dirty, or a signal it reads changed.

The gain is that an unrelated change elsewhere no longer costs anything in this subtree. On a large screen that is the difference between checking two thousand bindings and checking twenty.

As of Angular 22, OnPush is the default for new components, and the old always-check behaviour is the one you opt into.

Land it OnPush is a promise you make — that this component's output depends only on its inputs and its own signals — and mutating an input object in place is how you break that promise.

Likely follow-ups
"An OnPush component shows stale data. What is the first thing you check?"

Whether something mutated an object or array in place instead of replacing it. task.done = true on an object that was passed as an input leaves the reference identical, so OnPush correctly concludes the input did not change.

The fix is to replace — { ...task, done: true } — which is the same discipline signals need, so a codebase that follows it for signals gets OnPush correctness for free.

The other cause is data arriving from outside Angular's knowledge: a third-party library callback, or a WebSocket handler in a zoneless app. Those need the value written into a signal, which is what re-marks the component.

"What is markForCheck and how is it different from detectChanges?"

markForCheck() walks up from this component and marks the path to the root as dirty, so the next scheduled pass will not skip it. It does not render anything itself.

detectChanges() runs a check now, synchronously, on this component and its children. It is heavier, it bypasses the scheduler, and in development it can produce ExpressionChangedAfterItHasBeenChecked errors.

In signal-based code you should need neither. Reaching for detectChanges() in application code is usually a sign that some state is not in a signal.

Q30. "What does 'zoneless' mean, and what changes for you?"

Reveal answer

Strong answer Zoneless means the application runs without Zone.js, the library that used to patch every asynchronous browser API so Angular could notice that something happened.

Without it, Angular no longer guesses. Rendering is scheduled when a signal changes, when a template event handler runs, or when something explicitly marks a component dirty.

Three concrete gains: about 15 KB less JavaScript, no monkey-patching of native APIs so stack traces and third-party libraries behave normally, and no whole-tree checks triggered by unrelated timers.

It became stable in Angular 20.2 and is the default for new applications from Angular 21.

Land it The practical rule in a zoneless app is that all state a template reads must live in a signal — that is the whole migration, and it is also just good design.

Likely follow-ups
"What breaks when you turn zoneless on in an old app?"

Anything that changed a plain field and relied on Zone.js noticing. A setTimeout that assigns this.message = 'done' updates the field and never repaints, because nothing told Angular.

The same goes for callbacks from third-party libraries, WebSocket onmessage handlers, and ngOnDestroy cleanup that assumed a final check.

The fix for each is the same: put the state in a signal and set it. Where that is impractical during a migration, ChangeDetectorRef.markForCheck() is the bridge, but every use of it is a note that some state has not been converted yet.

"How would you migrate a large application to zoneless safely?"

Not in one commit. First move component state to signals and inputs to input(), feature by feature, while still on Zone.js — that work is valuable on its own and nothing breaks.

Then set every component to OnPush, which surfaces most of the same bugs while Zone.js is still there as a safety net, so failures are recoverable.

Only then switch the provider, and lean on end-to-end tests for the screens that involve third-party widgets, since those are where the remaining non-signal state hides.

Q31. "How do you test an Angular component, and what do you assert on?"

Reveal answer

Strong answer With TestBed, which builds a miniature application containing the component plus whatever providers I choose. Standalone components go in imports.

I create a fixture, call fixture.detectChanges() to render, then assert on what the user would see — the text on the screen, the number of rows, whether a button is disabled.

I do not assert on private fields or call internal methods, because those tests fail on every refactor and teach the team to delete them.

For services I usually skip TestBed entirely: a signal-based service is a plain class, so new TaskService() and assertions on its signals are faster and simpler.

Land it Test the contract with the user, not the shape of the implementation — that is what makes a test suite survive a rewrite of the component.

Likely follow-ups
"Why do tests need fixture.detectChanges()?"

Because a test has no running render loop. Changing a signal updates the value immediately, but nothing repaints until a change detection pass runs, and in a test you are the one who has to run it.

The classic symptom is a test that reads the DOM, sees the previous state, and fails in a way that looks like a component bug. The first thing I check in a mysteriously failing component test is a missing detectChanges after the state change.

For asynchronous work, await fixture.whenStable() before the final detectChanges, so pending promises and resources have settled.

"How do you test something that makes HTTP calls?"

With provideHttpClient() and provideHttpClientTesting(), then HttpTestingController. expectOne(url) asserts that exactly one request for that URL was made — so a typo in the endpoint fails the test instead of silently returning nothing.

req.flush(body) supplies the response, and req.flush(null, { status: 500, statusText: 'Server Error' }) lets me test the error branch, which is the branch people never cover.

http.verify() at the end fails if any request went unanswered, catching calls I did not expect the component to make.

Q32 · Scenario. "Your single-page app gets slower the longer it is open, and memory grows. Where do you look?"

Reveal answer

Strong answer A leak in a single-page application almost always means something is holding a destroyed component alive. I would work through four suspects in this order.

  1. Subscriptions that never complete. Router events, interval, fromEvent, form valueChanges, WebSockets. Each keeps a closure over the component. I grep for .subscribe( and check every one for takeUntilDestroyed().
  2. Listeners added by hand. addEventListener on window or document without a matching removeEventListener in cleanup.
  3. Third-party widgets. Charts, maps and editors usually have a destroy() method that has to be called; without it their internal listeners survive.
  4. Long-lived services holding component references — a store that keeps a callback or an element from a screen the user left.

To confirm rather than guess, I take a heap snapshot in Chrome DevTools, navigate away from the screen ten times, force garbage collection, take another snapshot and compare — a component class with a growing instance count is the answer.

Land it The snapshot comparison is the part that matters: it turns "I think it is the subscriptions" into a component name and a count.

Likely follow-ups
"How does takeUntilDestroyed work?"

It is an RxJS operator that completes the stream when the current injection context is destroyed. Called in a field initialiser or constructor it picks up the component's DestroyRef automatically; elsewhere you pass one in.

Its advantage over the old pattern — a destroy$ subject plus takeUntil plus an ngOnDestroy — is that the cleanup is written at the point of subscription, so it cannot be forgotten when someone adds a fourth subscription later.

"Do signals leak?"

Signals and computeds do not; they hold no subscription of their own, and a computed nobody reads is simply garbage collected.

Effects created in an injection context clean themselves up when it is destroyed, and so do resources. The risk is an effect created outside one with a manual injector, which keeps running until you destroy it.

The other real risk is a long-lived root service holding a signal that accumulates — a log array that grows forever is not a framework leak, but it is the same symptom.

Q33. "How does Angular protect against cross-site scripting, and how would you defeat that protection by accident?"

Reveal answer

Strong answer Angular treats all values bound into a template as untrusted and sanitises them for the context they land in. Interpolation escapes HTML entirely, so {{ userInput }} can never produce a live tag.

Binding to [innerHTML] is sanitised too: Angular strips <script> tags, event handler attributes and javascript: URLs before inserting the markup.

You defeat it in three ways. Calling bypassSecurityTrustHtml on user content, which is exactly what its name says. Writing to nativeElement.innerHTML directly, which never goes through Angular. Or building a template string on the server and rendering it, which turns a data problem into a code problem.

Land it The framework's protection is strong and the holes are all opt-in — so the review question is "does any bypassSecurityTrust call touch data a user can influence".

Likely follow-ups
"When is bypassSecurityTrust* legitimate?"

When the value comes from a source you control and Angular cannot know that — an embed URL from your own configuration, or SVG markup from a designer-maintained icon set in your repository.

The rule I apply is that the argument must never be traceable to user input, and the call should sit in one small, well-named service rather than scattered through components, so it is greppable in a review.

"What else would you check on the security side of a frontend?"

A Content Security Policy header, which is the backstop when sanitisation is bypassed, and Angular supports a nonce for its own inline styles.

No secrets in the bundle — API keys in the frontend are public, whatever the route or environment file. Authentication tokens in memory or a HttpOnly cookie rather than localStorage, which any injected script can read.

And the point from the guard question: every route guard has a matching server-side authorisation check, because the browser is not a trusted environment.

Q34. "What is the difference between ng serve and ng build, and what does a production build do?"

Reveal answer

Strong answer ng serve runs a development server that compiles in memory, watches files, and reloads the browser. Nothing is written to disk and nothing is optimised, because the priority is rebuild speed.

ng build writes an optimised bundle to dist/. It compiles templates ahead of time, tree-shakes unused code, minifies, hashes filenames for cache busting, splits lazy routes into separate chunks, and strips development-only checks.

The difference is large — a development bundle can be several times the size of the production one — which is why judging performance from ng serve is misleading.

Land it Always measure performance against a production build served over the network, not against the development server on localhost.

Likely follow-ups
"What are bundle budgets?"

Size limits declared in angular.json that make the build warn or fail when a bundle grows past them — typically a limit on the initial bundle and one on any single component's styles.

They matter because bundle growth is invisible in code review: nobody notices that an import of a date library added 200 KB. A failing build does notice.

I would set the initial budget near the current size rather than at some aspirational number, so it catches regressions rather than being permanently red and therefore ignored.

"Something made the bundle huge. How do you find it?"

ng build --stats-json and then a bundle analyser, which renders the bundle as a treemap where the biggest rectangle is the culprit.

The usual findings are a whole utility library imported for one function, a date library with every locale included, a chart or icon package imported as a barrel so nothing tree-shakes, or a "shared" module that pulls in a feature's worth of code.

The fixes in order: import the single function rather than the namespace; check the package ships an ES-module build so tree-shaking can work at all; and move genuinely heavy widgets behind @defer or a lazy route.

Q35. "How would you structure the folders of a large Angular application?"

Reveal answer

Strong answer By feature, not by technical type. A folder per feature containing that feature's components, services, models and routes — so everything a change touches is in one place.

Folders named components/, services/ and models/ at the top level look tidy and age badly: a single change means editing four folders, and nothing tells you which files belong together.

Alongside the features I keep a core/ for things there is exactly one of — authentication, interceptors, the error handler — and a shared/ for genuinely reusable presentational components with no feature knowledge.

Each feature gets its own lazy route, which makes the folder boundary and the bundle boundary the same line.

Land it The test for a good structure is whether a new engineer can delete a whole feature by deleting one folder — if that leaves dangling imports everywhere, the boundaries are not real.

Likely follow-ups
"How do you stop shared/ becoming a dumping ground?"

By defining it narrowly: a thing may live in shared/ only if it is used by two or more features and knows nothing about any of them. A component that takes a Task input is not shared, it is a task-feature component.

In a monorepo I would enforce it with lint rules on import boundaries — features may import from shared and core, shared may import from neither. Without enforcement the rule survives about a quarter.

"Should features import from each other?"

Preferably not directly, because that is how two features become one. If billing needs a customer name, it should go through a shared model and a service, not import a component out of the customers feature.

When two features genuinely need the same domain logic, that logic has outgrown both and belongs in its own module or library that both depend on. The dependency graph should stay a tree, not a mesh.

Q36 · Scenario. "A page with a 500-row table feels sluggish when typing in the filter box. Walk me through your diagnosis."

Reveal answer

Strong answer I would go in this order, cheapest check first.

  1. Is the filter a method call in the template? @for (t of filtered()) where filtered() is a component method runs the whole filter on every render. Turning it into a computed makes it run once per keystroke instead of many times.
  2. Is there a track, and is it stable? Without one, every keystroke destroys and rebuilds 500 rows. That alone can account for the whole symptom.
  3. How heavy is one row? 500 rows each with three pipes, a nested component and an icon is 500 times whatever that costs. I check with the Angular DevTools profiler, which attributes time per component.
  4. Is the input debounced? If each keystroke triggers a request or an expensive recomputation, a 200 ms debounce removes most of the work with no visible delay.
  5. Does the user actually need 500 rows? Virtual scrolling renders only the visible window, which turns 500 into about 20 regardless of the data size, and pagination sidesteps it entirely.

Land it I would fix the computed and the track first, then re-measure — those two are minutes of work and usually the whole problem, and virtual scrolling is a real change I would rather justify with a profile than assume.

Likely follow-ups
"How do you measure rather than guess?"

Angular DevTools has a profiler that records change detection cycles and shows a flame chart of time per component, so I can see which component dominates and how often it is being checked at all.

Chrome's own performance panel gives the wider picture — whether the time is in scripting, layout or paint, since a slow table can be CSS rather than Angular.

And I measure on a production build with CPU throttling, because a modern laptop hides a problem that a mid-range phone will not.

"What is virtual scrolling and what does it cost?"

It renders only the rows currently in view plus a small buffer, and translates a spacer element so the scrollbar behaves normally. Angular CDK provides it with cdk-virtual-scroll-viewport.

The costs are real: rows must have a known or measurable height, browser find-in-page only sees rendered rows, and anchor links into the middle of the list need extra work. Accessibility needs care too, since screen readers see a changing set of nodes.

So it is the right answer for thousands of rows and an over-engineered one for a hundred, where pagination or simply rendering less per row is cheaper to build and to maintain.

Q37. "What is an NgModule, and why does new code not have one?"

Reveal answer

Strong answer An NgModule was a container that declared which components belong to it, which of them other modules may use, and which providers it registers. Before standalone components, every component had to be declared in exactly one module.

It went away because it was ceremony that bought little. Using a component from elsewhere meant exporting it there, importing that module here, and the failure mode was an unhelpful error about an unknown element.

Standalone components declare their own imports, which puts the dependency list next to the thing that has the dependency. It also helps tree-shaking, because the compiler can see precisely what each component uses.

Modules still work and large codebases still contain them; they are legacy rather than removed.

Land it The migration is incremental and mechanical — ng generate @angular/core:standalone converts a project in stages, and standalone and module-based components interoperate throughout.

Likely follow-ups
"Can a standalone component use a component from an old NgModule?"

Yes. The standalone component imports the module, and everything that module exports becomes available to its template. That is how you use an older component library from new code.

The reverse also works: an NgModule can list a standalone component in its imports array rather than declarations, which is what lets a large application migrate one component at a time instead of in one commit.

"What replaced forRoot()?"

The provide* functions. Where a library used to expose SomeModule.forRoot(config) to register its singletons, it now exposes provideSomething(config) that you put in app.config.ts — provideRouter, provideHttpClient and provideAnimations are the ones you meet first.

They compose better: features are added with withInterceptors(...), withComponentInputBinding() and similar, so you only pay for what you switch on, and unused features tree-shake out.

Q38. "What is server-side rendering and when would you turn it on?"

Reveal answer

Strong answer Server-side rendering means Angular runs on the server, produces the HTML for the requested URL, and sends that. The browser shows real content immediately instead of an empty <app-root> waiting for JavaScript.

Then hydration happens: the client-side application starts, adopts the existing DOM instead of rebuilding it, and attaches its event listeners.

I would turn it on for anything public where first impressions or search ranking matter — marketing sites, e-commerce, content, public listings.

I would not bother for an internal tool behind a login. Search engines never see it, users load it once and keep the tab open all day, and the cost is a Node server in production plus a class of bugs where code assumes window exists.

Land it SSR buys you the first paint and the crawler; it costs you a server to run and a discipline about browser-only APIs — so it is a product decision, not a default.

Likely follow-ups
"What typically breaks under SSR?"

Anything touching browser globals at construction time — window, document, localStorage, navigator. On the server they do not exist, so the render throws while everything works locally.

The fix is to do that work in afterNextRender, which only runs in the browser, or to guard with isPlatformBrowser.

The other classic is a double fetch: the server loads data, then the client loads it again on startup. Angular's transfer-state mechanism serialises the server's responses into the page so the client reuses them, and httpResource participates in that automatically.

"What is incremental hydration?"

Hydrating parts of the page on demand rather than all at once. You combine @defer with a hydration trigger, and a section stays as plain server-rendered HTML until the user scrolls to it or interacts with it.

That matters because full hydration has to download and execute the JavaScript for the entire page before anything is interactive, which is why a server-rendered page can look ready and not respond to clicks. Incremental hydration cuts that initial work to the parts people actually touch.

Q39. "What do you do in an Angular app to make it accessible?"

Reveal answer

Strong answer Most of it is not Angular-specific, and that is the point. Use the right element — a <button> for something clickable, not a <div> with a click handler — because the native element brings keyboard support, focus and the correct role for free.

Label every form control with a <label for>, and connect error messages with aria-describedby so a screen reader announces the problem rather than just "invalid".

The Angular-specific parts are three. Announce route changes, because a single-page navigation is silent to a screen reader — moving focus to the new page's heading is the simplest fix. Manage focus when a dialog opens and return it when it closes. And be careful with @if, since removing the focused element sends focus to the body.

Land it The single highest-value habit is using native elements, because every hand-built substitute has to re-implement keyboard behaviour that the browser already ships.

Likely follow-ups
"How would you test accessibility?"

Three layers. An automated checker such as axe in the test suite, which catches contrast, missing labels and bad ARIA — perhaps a third of real issues, but cheaply and on every commit.

A keyboard pass by hand: tab through the screen and confirm every interactive thing is reachable, the focus ring is visible, and the order matches the visual layout. That finds most of what automation misses.

Then a screen reader on the critical flows. Angular's CDK also provides LiveAnnouncer for announcing changes and a focus trap for dialogs, which removes most of the hand-written work.

Q40 · Design. "Design the front end for a searchable, sortable, paginated table of a hundred thousand records. Talk me through it."

Reveal answer

The real test Whether you move the work to the server without being told, and whether you name the URL as state.

Strong answer The first decision settles everything else: with a hundred thousand records, searching, sorting and paging all happen on the server. The browser holds one page at a time.

So the client's state is small — search text, sort column, sort direction, page number, page size — and I would keep it in the URL as query parameters rather than in component fields. That makes the view shareable, bookmarkable, and correct across a browser refresh and the back button, which are the three things users actually complain about.

With withComponentInputBinding() those parameters arrive as signal inputs. An httpResource reads them to build its URL, so any change re-fetches automatically and cancels the in-flight request.

The remaining pieces are ordinary care. Debounce the search box by about 250 ms. Render all four states, so a failed request shows a retry rather than an empty table. Keep the previous page visible while the next one loads instead of flashing a spinner. And use cursor-based paging if the data changes while people are reading it, because offset paging skips and repeats rows when the underlying set shifts.

Things I would deliberately not do: fetch all hundred thousand rows and filter in the browser, and reach for virtual scrolling — pagination already bounds the DOM, so virtual scrolling would add complexity for nothing.

Land it The design decision worth defending is putting the table's state in the URL: it costs one provider line and it turns three recurring bug reports into features.

Likely follow-ups
"How do you keep the table from flickering on every keystroke?"

Keep rendering the previous rows while the new request is in flight, and show the loading state as a subtle bar rather than by replacing the table with a spinner. A resource's status() distinguishes 'loading' from 'reloading', which is exactly this case.

Combined with debouncing, the table then updates about once per pause in typing rather than flashing empty five times a second.

"The user selects rows, then changes the filter. What happens to the selection?"

It has to be a deliberate decision, and either answer can be right as long as it is visible. Clearing it is honest and simple, and linkedSignal over the filter does exactly that in one line.

Keeping it across filters means storing selected ids rather than row objects, and showing a count like "3 selected, 1 not shown by the current filter" — otherwise the user submits a bulk action on rows they cannot see, which is how accidents happen.

What is not acceptable is silently keeping a selection that the screen no longer displays.

"Where would you put the sort and filter logic if the backend cannot do it?"

Then the volume has to come down before it reaches the browser, because a hundred thousand rows of JSON is tens of megabytes and the parse alone will freeze the tab.

If the real dataset is small enough after all, a computed chain — filter, then sort, then slice for the page — is the right shape, since each step is cached and only reruns when its own inputs change.

If it genuinely is large and the server genuinely cannot help, I would push back on the requirement rather than engineer around it, because every browser-side answer here is a worse version of an index.

14 · RecapWhat You Can Do Now

  • You can explain what a framework is for — keeping the screen in agreement with the data — and place any Angular feature inside the four ideas: component, signal, dependency injection, router
  • You can generate an application with the CLI and explain every generated file, including the five-line startup path from main.ts to a rendered component
  • You can read and write the TypeScript Angular needs: interfaces, unions, narrowing, generics, nullability, and classes with decorators
  • You can build components with all four bindings, use @if, @for and @switch, and say why track is required and what breaks without a stable one
  • You can model state with signal, derive it with computed, reach outside with effect, and explain why replacing beats mutating
  • You can pass data down with input(), report events up with output(), project markup with <ng-content>, and defend unidirectional data flow
  • You can write a service as a signal store with a private writable signal and a read-only public view, and choose deliberately between root-provided and component-provided
  • You can fetch data with httpResource, handle all four screen states, write to a server with HttpClient, and put cross-cutting concerns in an interceptor
  • You can configure routes with lazy loading, read parameters as component inputs, and explain why a guard is user experience rather than security
  • You can build a reactive form with validation, show errors at a moment that is not annoying, and name what Signal Forms change
  • You can test a service without TestBed, test a component by asserting on what the user sees, and stub HTTP with HttpTestingController
  • You can answer the forty-question canon out loud, including the follow-ups

There are no dumb questions

Do I have to learn RxJS to be productive in Angular now?
Not to start. Signals and httpResource cover component state and data fetching, which is most of an application. You need RxJS the moment you meet a real stream — typing that must be debounced, a WebSocket, several requests that must be coordinated or cancelled — and you will meet plenty of it in existing code. Chapter E15 teaches it properly.
Everything I find online uses *ngIf and NgModule. Am I learning the wrong thing?
No — you are learning the current thing while most published material describes 2021. Both forms work, they interoperate, and this chapter shows you the old syntax beside the new one precisely so old articles stay readable. When you follow a tutorial, check its date first; anything before 2024 predates standalone-by-default, signals and built-in control flow.
Should I learn Angular or React?
For employability, whichever the companies near you hire for — and in enterprise, banking, telecom, healthcare and internal tooling that is very often Angular. For understanding, learning both is worth more than learning either twice, because the second one teaches you which parts were the framework and which parts were the problem. Chapter E16 compares them directly.
My component works but I do not understand why. Is that fine?
It is normal, and it is the exact gap this chapter's hook describes. The repair is small: take the thing that works and break it on purpose. Remove the track, drop the parentheses from a signal read, mutate an array instead of replacing it. Watching each specific failure is what converts a memorised incantation into knowledge you can debug with.
How long until I am employable in Angular?
With daily practice, the honest range is two to three months to a junior standard: this chapter's material plus three or four applications you built rather than followed. What shortens it is building something nobody wrote a tutorial for, because that is where you meet the errors that tutorials never trigger.
Do I need Angular Material?
No, and it is worth building a few components yourself first so you know what a component library is doing for you. Once you reach real work, a mature library saves an enormous amount of accessibility and keyboard-handling effort. Angular Material is the official one; the CDK underneath it is genuinely useful on its own for focus trapping, overlays and virtual scrolling.
🧠 Flex your memory

Close the page and write down, from memory: the four bindings and which direction each moves data; the difference between signal, computed and effect in one sentence each; and exactly why pushing into an array held by a signal fails to update the screen. Then reach back to Chapter E11: JavaScript's const does not stop you mutating an object it points at — explain how that single fact is the root of both the signal mutation trap and the OnPush stale-data bug.