Blog

Part 26 · Change Detection in Angular 22: OnPush by Default, Zoneless and Signals

Change detection is how Angular keeps the screen in step with your data. This part shows which components Angular checks after a click, a signal write or a new input, and why a plain field in a timer is missed.

Since Part 3 we’ve leaned on one rule: a component is redrawn after an event in its template, or when a signal its template read changes. That rule was enough to write working pages. This part opens it up. We’ll see exactly which components Angular checks, which it skips, and what makes it start at all.

This part covers what change detection is, OnPush (the default in Angular 22), what makes an OnPush component get checked, how a new zoneless app decides when to render, how a signal marks only the views that read it, the Eager strategy and zone.js in older code, and how to see checks for yourself. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts. It has three components: App holds a Title and a Counter. Each template calls a checked() method that logs a line and returns an empty string, so it adds nothing to the page. A method called from a template runs every time Angular checks that template, so each line in the console means “Angular just checked this one”.

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-title',
  template: `<h1>Shop{{ checked() }}</h1>`,
})
export class Title {
  protected checked() {
    console.log('Title checked');
    return '';
  }
}

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}{{ checked() }}</p>
    <button (click)="addOne()">Add one</button>
    <button (click)="addOneLater()">Add one later</button>
  `,
})
export class Counter {
  protected readonly count = signal(0);

  protected addOne() {
    this.count.update((n) => n + 1);
  }

  protected addOneLater() {
    setTimeout(() => this.count.update((n) => n + 1), 1000);
  }

  protected checked() {
    console.log('Counter checked');
    return '';
  }
}

@Component({
  selector: 'app-root',
  imports: [Title, Counter],
  template: `
    <app-title />
    <app-counter />
    {{ checked() }}
  `,
})
export class App {
  protected checked() {
    console.log('App checked');
    return '';
  }
}

Open the browser’s Console tab (F12). When the page loads, it shows:

App checked
Title checked
Counter checked

Every component is checked once, to draw it. Now guess before you read on. You click Add one. Which lines appear? Then you click Add one later, and a second later the timer changes count. Which lines appear then?

Here’s what happens. Click Add one, and the console gets two lines:

App checked
Counter checked

Title wasn’t checked. App was, even though nothing in App changed. Now click Add one later. The click itself gives the same two lines:

App checked
Counter checked

A second later, the timer calls count.update, and the console gets one line:

Counter checked

and the page shows:

Shop
Count: 2
Add oneAdd one later

(The two buttons show as Add oneAdd one later because buttons sit on one line, and the page text runs them together.)

So a click checked the clicked component and its parent. A signal write from a timer checked only the component that read the signal. The rest of this part explains both.

What change detection is

Your templates say what the screen should show: Count: {{ count() }}. The screen is real DOM: a <p> element with the text Count: 0. When count changes, something has to bring the DOM in line with the template again. In Angular, that something is change detection.

To check a component, Angular runs its template’s bindings, compares each value with the one it used last time, and touches the DOM only where a value differs. Earlier parts called this a redraw. The template’s code runs, but the DOM changes only where needed. That’s why our checked() method runs on every check: it’s a binding, so it’s part of the template’s code.

Angular doesn’t check on its own. Something has to tell it a check is needed. Then it runs a render: one pass down the component tree, from App at the top to the components inside it. On the way, it decides for each component whether to check it or skip it. Look at the order of the first log above. App comes first, even though its checked() call is at the end of its template. Angular finishes a parent’s own bindings before it goes down into its children.

OnPush is the default

How does Angular decide whether to check a component? Each component has a change detection strategy. In Angular 22, every component is OnPush unless it says otherwise. You don’t write anything for it. The note in Angular 22.3’s own type definitions for ChangeDetectionStrategy.OnPush says it plainly: “NOTE: OnPush is enabled by default.”

An OnPush component is skipped during a render unless one of these is true:

  1. A signal its template read has changed. This is the one you’ll rely on most. This includes host bindings of directives in that template, such as the ng-valid classes in Part 23.
  2. An input got a new value. The parent was checked, and a binding like [user]="user()" produced a different value from last time. For an object or a list, “different” means a different reference: a new object, not the same object with a changed property.
  3. An event happened in its template, or in a child’s template. A (click) handler in Counter marks Counter and every component above it, all the way up to the root.
  4. Code asked for it with markForCheck(). This is how older code does it. We’ll meet it below.

Now the Try-this-first logs make sense. The click in Counter marked Counter and its parent App (rule 3). Title had none of the four, so Angular skipped it. The timer changed count, which only Counter‘s template read (rule 1). Nothing marked App, so its template didn’t run. Angular still passed through App on the way down, because Counter is inside it. It just didn’t run App‘s bindings.

How a signal marks only the views that read it

Here’s that second case, step by step. The dashed blue arrow means “reads”. A highlighted outline means “this template runs”. A grey box with a red label means it was skipped.

component tree App not checked on the path checked Title not checked Counter Count: 0 Count: 1 Count: 2 checked count: 0 count: 1 count: 2 a timer: count.update() marked a click: addOne() first render done: all three were checked once Counter marked; App marked only as the way to it one template ran: Counter's two templates ran: App's and Counter's Counter's template reads count(). Nothing else does A timer writes count. Only its reader is marked The render walks down from App and runs only Counter Compare: a click marks Counter and every parent above it

A signal write marks only the templates that read it. A template event marks the component and every parent above it.

Here are those steps in words, in case the animation doesn’t play for you:

  1. After the first render, every component has been checked once. Counter‘s template read count() while it ran, so Angular knows Counter depends on count. Nothing else read it.
  2. A timer calls count.update((n) => n + 1), and count becomes 1. The signal tells its readers. Counter is marked as needing a check. App gets a weaker mark: “a component inside me needs a check”. Angular schedules a render.
  3. The render starts at App. App‘s own template doesn’t run, because only the weaker mark is on it. Angular goes down into its children. Title has no mark, so it’s skipped. Counter is marked, so its template runs, and the text changes to Count: 1.
  4. For comparison, a click in Counter calls addOne(). An event marks its component and every parent as needing a check. So App‘s template runs, then Counter‘s. Title is still skipped.

Explain it like I’m ten

Picture a teacher and a classroom. The teacher can’t watch every desk at once, so the class has two rules.

Rule one: if your answer changes, raise your hand. The teacher walks from the front of the room straight to your desk and looks at your work. She walks past the other desks on the way, but she doesn’t stop at them. That’s a signal write. Only the reader of the signal gets checked.

Rule two: if you ask a question out loud, the teacher checks your desk, and also the desk of every class helper between the front and you, because a question might affect them too. That’s a click. It marks the component and its parents.

A desk where nobody raised a hand or asked anything doesn’t get looked at. That’s OnPush.

The precise version

Each component view has a reactive consumer for its template, like the one a computed has. While the template runs, every signal it calls is recorded as a dependency. When one of those signals changes, the consumer is marked dirty, every ancestor view gets a “has a child view to refresh” flag, and the scheduler is told. In the render, Angular walks the tree from the root. A view with only the ancestor flag isn’t refreshed, but Angular goes down into it. A view whose consumer is dirty is refreshed, if one of its signals really changed. A template or host listener does something different: it marks its view and every ancestor up to the root as needing a refresh, so all their templates run. When a view is refreshed, Angular checks its child components too: an OnPush child runs only if it’s marked or an input binding changed; an Eager child always runs.

Where the analogy breaks: the teacher doesn’t come the moment a hand goes up. Angular waits until your code has finished and then does one render, so three writes in one handler give one check. Also, a component can be checked when only its inputs changed, with no hand raised at all. The parent’s check passes the new value down, and that alone marks the child.

Zoneless: what schedules a render

The rules above decide which components a render checks. Something else decides whether a render happens. A new Angular 22 project has no zone.js (more on that below). Angular is zoneless: it renders only when one of its own APIs tells it to. Angular 22.3’s type definitions list them under provideZonelessChangeDetection(), which is already on by default. The ones you’ll meet are:

  • a signal that a template read changes;
  • a template or host listener runs, like (click);
  • ComponentRef.setInput(), which code that creates components on the fly uses to set an input;
  • ChangeDetectorRef.markForCheck();
  • a view is removed, or a view that’s already marked is attached.

Each one schedules a render. It doesn’t render straight away. It runs a little later, once your code has finished, and many notifications before then share one render.

What’s not on the list: a plain field changed in a setTimeout, in a setInterval, or after an await. Angular can’t see an assignment to a field. Part 3 showed the timer case. Promises have a twist worth seeing once:

// src/app/app.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <p>{{ status }}</p>
    <button (click)="saveNow()">Save now</button>
    <button (click)="saveSlow()">Save slow</button>
  `,
})
export class App {
  protected status = 'Not saved';

  protected async saveNow() {
    await Promise.resolve();
    this.status = 'Saved now';
  }

  protected async saveSlow() {
    await new Promise((resolve) => setTimeout(resolve, 100));
    this.status = 'Saved slow';
  }
}

async and await are plain JavaScript. await pauses the method until the promise after it settles, and the rest of the method runs later. Promise.resolve() is a promise that has already settled. The new Promise(...) settles 100 milliseconds later, like a slow server.

Click Save now. The page shows:

Saved now
Save nowSave slow

It worked. Now reload the page, click Save slow and wait. The page shows:

Not saved
Save nowSave slow

Both methods set a plain field after an await. Neither tells Angular. The difference is timing. The click scheduled a render, and Angular runs it on the next timer or animation frame. A promise that has already settled continues before that, every time, so the render picked up Saved now. It works only because nothing slow happened before the field changed. The slow promise settled after the render, and nothing scheduled another one. A real server answers long after that render, so the “now” version hides a bug that shows up in production. Make status a signal and both work.

Inputs: a new value, not a changed one

Rule 2 says an input marks its component when it gets a new value. For an object, Angular compares references, the same way a signal does. Here a UserCard gets a user object from App:

// src/app/app.ts
import { Component, input, signal } from '@angular/core';

interface User {
  name: string;
  age: number;
}

@Component({
  selector: 'app-user-card',
  template: `<p>Card: {{ user().name }} is {{ user().age }}{{ checked() }}</p>`,
})
export class UserCard {
  readonly user = input.required<User>();

  protected checked() {
    console.log('UserCard checked');
    return '';
  }
}

@Component({
  selector: 'app-root',
  imports: [UserCard],
  template: `
    <p>App: {{ user().name }} is {{ user().age }}</p>
    <app-user-card [user]="user()" />
    <button (click)="birthdayInPlace()">Birthday in place</button>
    <button (click)="birthday()">Birthday</button>
  `,
})
export class App {
  protected readonly user = signal<User>({ name: 'Ana', age: 10 });

  protected birthdayInPlace() {
    this.user().age++;
  }

  protected birthday() {
    this.user.update((u) => ({ ...u, age: u.age + 1 }));
  }
}

The page loads, and the console shows UserCard checked once. Now click Birthday in place. The page shows:

UserCard checked
App: Ana is 11
Card: Ana is 10
Birthday in placeBirthday

and nothing new is logged. The two lines disagree. The click marked App, so App‘s template ran and read the changed age. Then Angular looked at the binding [user]="user()". It’s the same object as last time, so the input didn’t change, nothing marked UserCard, and Angular skipped it.

Now click Birthday. It builds a new object, as Part 3 taught. The page shows:

App: Ana is 12
Card: Ana is 12
Birthday in placeBirthday

and the console gets one line:

UserCard checked

The new reference changed the input, and that marked UserCard. The 11 from before was in the object all along. The card just wasn’t asked to look.

Eager: checked whenever its parent is

OnPush has one alternative, called Eager. An Eager component is checked every time Angular checks its parent, whether or not anything marked it. Here’s the Try-this-first page with Title switched to Eager:

// src/app/app.ts
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';

@Component({
  selector: 'app-title',
  changeDetection: ChangeDetectionStrategy.Eager,
  template: `<h1>Shop{{ checked() }}</h1>`,
})
export class Title {
  protected checked() {
    console.log('Title checked');
    return '';
  }
}

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}{{ checked() }}</p>
    <button (click)="addOne()">Add one</button>
    <button (click)="addOneLater()">Add one later</button>
  `,
})
export class Counter {
  protected readonly count = signal(0);

  protected addOne() {
    this.count.update((n) => n + 1);
  }

  protected addOneLater() {
    setTimeout(() => this.count.update((n) => n + 1), 1000);
  }

  protected checked() {
    console.log('Counter checked');
    return '';
  }
}

@Component({
  selector: 'app-root',
  imports: [Title, Counter],
  template: `
    <app-title />
    <app-counter />
    {{ checked() }}
  `,
})
export class App {
  protected checked() {
    console.log('App checked');
    return '';
  }
}

Click Add one, then Add one later, and wait. Since the page loaded, the console shows:

App checked
Title checked
Counter checked
App checked
Title checked
Counter checked
App checked
Title checked
Counter checked
Counter checked

The first three lines are the first render. Each click checked App, so Title came along every time. The timer didn’t check App, so it didn’t check Title either. In a zoneless app, Eager doesn’t mean “always”. It means “always when the parent is checked”.

ChangeDetectionStrategy has three names in Angular 22.3: OnPush (the default), Eager, and Default. Default is the old name for Eager, kept so old code still builds, and marked deprecated. A new component almost never needs Eager. It’s there for older components that keep state in plain fields.

Worked example: a scoreboard that checks too much

A store (from Part 15) holds the scores of two teams. Each TeamRow shows one team. Record<string, number> is a TypeScript type for an object whose keys are strings and whose values are numbers. { ...s, [team]: s[team] + 1 } makes a new object, with the key in square brackets taken from the team variable.

// src/app/score-store.ts
import { Service, signal } from '@angular/core';

@Service()
export class ScoreStore {
  private readonly state = signal<Record<string, number>>({ Red: 0, Blue: 0 });
  readonly scores = this.state.asReadonly();

  score(team: string) {
    this.state.update((s) => ({ ...s, [team]: s[team] + 1 }));
  }
}
// src/app/team-row.ts
import { Component, inject, input } from '@angular/core';
import { ScoreStore } from './score-store';

@Component({
  selector: 'app-team-row',
  template: `<p>{{ team() }}: {{ store.scores()[team()] }}{{ checked() }}</p>`,
})
export class TeamRow {
  readonly team = input.required<string>();
  protected readonly store = inject(ScoreStore);

  protected checked() {
    console.log(`${this.team()} row checked`);
    return '';
  }
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { ScoreStore } from './score-store';
import { TeamRow } from './team-row';

@Component({
  selector: 'app-root',
  imports: [TeamRow],
  template: `
    <app-team-row team="Red" />
    <app-team-row team="Blue" />
    <button (click)="store.score('Red')">Red scores</button>
  `,
})
export class App {
  protected readonly store = inject(ScoreStore);
}

team="Red" without square brackets passes the plain text Red to the input. The page loads with one line per row. Click Red scores. The page shows:

Red: 1
Blue: 0
Red scores

and since the page loaded, the console shows:

Red row checked
Blue row checked
Red row checked
Blue row checked

The Blue row was checked, but its score didn’t change. Both rows read store.scores(), and scores is a new object after every point. So every row that read it is marked, whichever team scored.

The fix is to have each row read only what it shows. A computed in the row picks out its own team’s score:

// src/app/team-row.ts
import { Component, computed, inject, input } from '@angular/core';
import { ScoreStore } from './score-store';

@Component({
  selector: 'app-team-row',
  template: `<p>{{ team() }}: {{ score() }}{{ checked() }}</p>`,
})
export class TeamRow {
  readonly team = input.required<string>();
  private readonly store = inject(ScoreStore);
  protected readonly score = computed(() => this.store.scores()[this.team()]);

  protected checked() {
    console.log(`${this.team()} row checked`);
    return '';
  }
}

Click Red scores again. The page shows the same text:

Red: 1
Blue: 0
Red scores

but this time the console shows:

Red row checked
Blue row checked
Red row checked

Both rows still heard that scores changed. But when the render reached the Blue row, Angular first asked its score whether it really changed. score ran again and came out as 0, equal to before, so it counts as unchanged (Part 3), and the Blue row’s template didn’t run. The template now depends on one number instead of the whole object.

With two rows this saves nothing you’d notice. The habit matters on a page with hundreds of rows. Don’t go looking for this everywhere. Count the checks, as we did here, when a page feels slow.

Worked example: counting checks on the page, and NG0600

Logging works, but you might want the count on the screen. A first try keeps it in a signal:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <p>Count: {{ count() }}{{ countCheck() }}</p>
    <p>Checks: {{ checks() }}</p>
    <button (click)="addOne()">Add one</button>
  `,
})
export class App {
  protected readonly count = signal(0);
  protected readonly checks = signal(0);

  protected addOne() {
    this.count.update((n) => n + 1);
  }

  protected countCheck() {
    this.checks.update((n) => n + 1);
    return '';
  }
}

It builds. But the page shows almost nothing:

Add one

and the console has a red error. Its first line is:

ERROR RuntimeError: NG0600: Writing to signals is not allowed while Angular renders the template (eg. interpolations). Template location: '_App' component. Signal: 'checks'. Find more at https://v22.angular.dev/errors/NG0600

Read it piece by piece:

  • NG0600 is Angular’s error code. The link at the end explains it on angular.dev, for the 22 docs.
  • Writing to signals is not allowed while Angular renders the template is the rule. A template’s bindings may read signals but not change them.
  • Template location: '_App' component says which template did it. The build named the class _App; it’s our App.
  • Signal: 'checks' names the signal that was written.

Why the rule? A write during a check would mark the template again, the template would write again, and the render would never end. Angular stops it at the first write. The error broke the first render, so the <p> elements stayed empty and only the button text showed.

The fix is to not use a signal for this. The check counter isn’t app state. It’s a probe that watches the template, and it must not cause a check itself. A plain field does the job, because writing it tells Angular nothing:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <p>Count: {{ count() }}{{ countCheck() }}</p>
    <p>Checks: {{ checks }}</p>
    <button (click)="addOne()">Add one</button>
  `,
})
export class App {
  protected readonly count = signal(0);
  protected checks = 0;

  protected addOne() {
    this.count.update((n) => n + 1);
  }

  protected countCheck() {
    this.checks++;
    return '';
  }
}

Click Add one twice. The page shows:

Count: 2
Checks: 3
Add one

Three checks: the first render and two clicks. It works because countCheck() runs before {{ checks }} in the same template, so the number is read after it was bumped. Keep this for debugging only.

Seeing checks with tools

Logging from a template method, as we’ve done all along, is the simplest tool, and it works in any browser. Two others are worth knowing:

  • Angular DevTools is a browser extension for Chrome and Firefox. Its Profiler tab records while you use the page. Each bar is one change detection run. Select a bar to see which components were checked and how long each took. A Change detection checkbox above the flame graph greys out the components that weren’t checked.
  • enableProfiling(), from @angular/core, sends Angular’s own events to the Performance panel of Chrome’s developer tools, so a recorded profile shows Angular’s work by name. Its type definitions say it works only in development mode. Call it once in main.ts, before bootstrapApplication.

In older code

Before Angular 21, new projects loaded zone.js. You’ll find it in package.json and in the polyfills list in angular.json, and in projects made with Angular 18 to 20, provideZoneChangeDetection({ eventCoalescing: true }) in app.config.ts. Zone.js wraps setTimeout, promises, DOM events and network calls, and tells Angular after any of them finishes. Angular then runs a render over the whole tree. Most older components are Eager (written as the default, or as ChangeDetectionStrategy.Default), so they’re checked on every one of those renders, and plain fields just work. In those projects a component with no changeDetection line was Eager. When such a project is updated to Angular 22, ng update adds changeDetection: ChangeDetectionStrategy.Eager to every component, so they keep working as before.

If you add provideZoneChangeDetection() to a new project without installing zone.js, the app doesn’t start. The console shows NG0908: In this configuration Angular requires Zone.js.

Older OnPush components that don’t use signals tell Angular about changes by hand, with ChangeDetectorRef:

// src/app/app.ts
import { ChangeDetectorRef, Component, inject } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <p>{{ status }}</p>
    <button (click)="save()">Save</button>
  `,
})
export class App {
  private readonly cdr = inject(ChangeDetectorRef);
  protected status = 'Not saved';

  protected save() {
    setTimeout(() => {
      this.status = 'Saved';
      this.cdr.markForCheck();
    }, 100);
  }
}

Click Save and wait. The page shows:

Saved
Save

markForCheck() marks this component and its parents, like a click does, and schedules a render. You’ll also see detectChanges(), which checks the component and its children right away instead of waiting for a render. The async pipe from Part 12 calls markForCheck() each time its Observable sends a new value. That’s why it works in OnPush components. Older code may also write changeDetection: ChangeDetectionStrategy.OnPush on every component. In Angular 22 that line changes nothing.

Best practices

  • Use a signal for every value a template shows and that can change. Then rule 1 covers it, wherever the change comes from. It replaces plain fields plus markForCheck() calls.
  • Leave the strategy alone. OnPush is the default; don’t write it, and don’t reach for Eager to fix a stale screen. Find the plain field and make it a signal instead.
  • Pass new objects and lists to inputs. Build them with update((u) => ({ ...u, ... })). A changed reference is what marks the child. It replaces mutating in place and wondering why a child is stale.
  • Have each template read only what it shows. A small computed that picks out one value stops a big store from marking every reader. Measure with logs or the DevTools Profiler first.
  • Debug with a log in a template method. It shows exactly which templates ran. Remove it before you ship.

Tips and traps

  • A stale child next to a fresh parent. The parent shows the new value, the child the old one. You changed an object in place, so the input didn’t change. Give the parent’s signal a new object.
  • A plain field that works after await in a quick local try and fails in production. A fast promise continues before the click’s render; a real server doesn’t. Make the field a signal.
  • A plain field in a parent that updates only after a click in a child. The click marks every parent, so the parent’s template runs and picks up the field as a side effect. A timer’s change to the same field stays unseen. Make it a signal.
  • NG0600 in the console. A template binding wrote to a signal. Templates read; handlers and effects write. Move the write out of the template.
  • Expecting Eager to update from a timer. In a zoneless app, Eager runs only when its parent is checked. A timer that changes a plain field still goes unseen.
  • Copying provideZoneChangeDetection() from an old project. Without zone.js installed, the app fails with NG0908. A new project doesn’t need it.

Angular checks a component when a signal it read changes, when its input gets a new value, or when an event happens inside it, and a plain field tells it nothing.

Exercises

Exercise 1. Without running it, which lines does this log when you click Press? App holds Left and Right, and Right holds Leaf.

// src/app/app.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-leaf',
  template: `<button (click)="press()">Press</button>{{ checked() }}`,
})
export class Leaf {
  protected press() {}

  protected checked() {
    console.log('Leaf checked');
    return '';
  }
}

@Component({
  selector: 'app-left',
  template: `<p>Left{{ checked() }}</p>`,
})
export class Left {
  protected checked() {
    console.log('Left checked');
    return '';
  }
}

@Component({
  selector: 'app-right',
  imports: [Leaf],
  template: `<app-leaf />{{ checked() }}`,
})
export class Right {
  protected checked() {
    console.log('Right checked');
    return '';
  }
}

@Component({
  selector: 'app-root',
  imports: [Left, Right],
  template: `<app-left /><app-right />{{ checked() }}`,
})
export class App {
  protected checked() {
    console.log('App checked');
    return '';
  }
}

Exercise 2. App passes a list to ItemCount. Click Add eggs, and the count stays at 1. Why? Fix it.

// src/app/app.ts
import { Component, input, signal } from '@angular/core';

@Component({
  selector: 'app-item-count',
  template: `<p>{{ items().length }} items</p>`,
})
export class ItemCount {
  readonly items = input.required<string[]>();
}

@Component({
  selector: 'app-root',
  imports: [ItemCount],
  template: `
    <app-item-count [items]="items()" />
    <button (click)="add()">Add eggs</button>
  `,
})
export class App {
  protected readonly items = signal(['milk']);

  protected add() {
    this.items().push('eggs');
  }
}
1 items
Add eggs

Exercise 3. Rewrite the markForCheck() example from “In older code” with a signal, so it needs no ChangeDetectorRef.

Answers

1. Three lines: App, Right and Leaf. The click marks Leaf and every component above it, so App and Right are checked too. Left isn’t on that path and has no other mark. Parents come before children. Here’s the run:

// src/app/app.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-leaf',
  template: `<button (click)="press()">Press</button>{{ checked() }}`,
})
export class Leaf {
  protected press() {}

  protected checked() {
    console.log('Leaf checked');
    return '';
  }
}

@Component({
  selector: 'app-left',
  template: `<p>Left{{ checked() }}</p>`,
})
export class Left {
  protected checked() {
    console.log('Left checked');
    return '';
  }
}

@Component({
  selector: 'app-right',
  imports: [Leaf],
  template: `<app-leaf />{{ checked() }}`,
})
export class Right {
  protected checked() {
    console.log('Right checked');
    return '';
  }
}

@Component({
  selector: 'app-root',
  imports: [Left, Right],
  template: `<app-left /><app-right />{{ checked() }}`,
})
export class App {
  protected checked() {
    console.log('App checked');
    return '';
  }
}

The first render logs all four. Then click Press, and the console gets:

App checked
Left checked
Right checked
Leaf checked
App checked
Right checked
Leaf checked

2. push changes the array that’s already in the signal. The signal still holds the same array, so it notifies nobody. The click marks App, and App is checked, but the binding [items]="items()" gives the same array as last time, so ItemCount‘s input doesn’t change and it’s skipped. Give the signal a new array:

// src/app/app.ts
import { Component, input, signal } from '@angular/core';

@Component({
  selector: 'app-item-count',
  template: `<p>{{ items().length }} items</p>`,
})
export class ItemCount {
  readonly items = input.required<string[]>();
}

@Component({
  selector: 'app-root',
  imports: [ItemCount],
  template: `
    <app-item-count [items]="items()" />
    <button (click)="add()">Add eggs</button>
  `,
})
export class App {
  protected readonly items = signal(['milk']);

  protected add() {
    this.items.update((list) => [...list, 'eggs']);
  }
}

Click Add eggs. The page shows:

2 items
Add eggs

3. Make status a signal. Its write from the timer schedules the render, so the ChangeDetectorRef goes away:

// src/app/app.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <p>{{ status() }}</p>
    <button (click)="save()">Save</button>
  `,
})
export class App {
  protected readonly status = signal('Not saved');

  protected save() {
    setTimeout(() => this.status.set('Saved'), 100);
  }
}

Click Save and wait. The page shows:

Saved
Save

What’s next

So far every component’s code is in the first bundle the browser downloads. In Part 27, we’ll use @defer and lazy routes to load parts of the page only when they’re needed, and look at bundle budgets and NgOptimizedImage.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.