Blog

Part 8 · Signals, Part 2: effect, linkedSignal and untracked

Run code when signals change with effect, and why computed is usually the better tool. Read a signal without depending on it with untracked, and keep a selection that resets with linkedSignal.

In Part 3 a signal held a value, and computed() worked out new values from it. Both only hold values. Sometimes you need to do something when a signal changes: save it, log it, or hand it to code that isn’t Angular. And sometimes you need a value that’s worked out from a signal, like a computed, but that the user can also change.

This part covers effect() for the first job, linkedSignal() for the second, untracked() for reading a signal without depending on it, and custom equality. It also covers when not to use an effect, which is most of the time. 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 a count, a computed label for the template, and an effect that logs the count. The console.log lines show when each piece of code runs.

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

@Component({
  selector: 'app-root',
  template: `
    <p>{{ label() }}</p>
    <button (click)="addThree()">Add three</button>
    <button (click)="nothing()">Do nothing</button>
  `,
})
export class App {
  protected readonly count = signal(0);
  protected readonly label = computed(() => {
    console.log('computing label');
    return `Count: ${this.count()}`;
  });

  constructor() {
    console.log('constructor');
    effect(() => console.log('effect sees', this.count()));
  }

  protected addThree() {
    this.count.update((n) => n + 1);
    this.count.update((n) => n + 1);
    this.count.update((n) => n + 1);
    console.log('handler done');
  }

  protected nothing() {}
}

The constructor is a method that runs once, when Angular creates the component. We’ll come back to why the effect is created there.

Before you read on, guess. Open the browser’s Console tab (F12). What does it print when the page loads? How many effect sees lines does Add three add, and do they come before or after handler done? What does Do nothing add?

When the page loads, the console shows:

constructor
effect sees 0
computing label

Click Add three. The console adds:

handler done
effect sees 3
computing label

Click Do nothing. The console adds nothing at all:

Three changes to count gave one effect run, with the final value 3, after the handler had finished.

effect(): code that runs when signals change

effect() takes a function. Angular runs it once, notes which signals it read, and runs it again whenever one of those signals changes. You import effect from @angular/core, like signal and computed.

That sounds like a computed, and the tracking works the same way. The difference is what it’s for. A computed returns a value, and runs only when someone reads it. An effect returns nothing. It runs for what it does: a log line, a save, a call into another library. Nobody reads an effect, so Angular has to run it on its own schedule.

Here’s that schedule, from the logs above:

  • The first run happens after the constructor has finished, not inside it. The constructor logged first, then the effect.
  • An effect runs before the template. effect sees 0 came before computing label, which is the template reading label(). For an effect created in a component, Angular runs it during the redraw, just before it checks that component’s template. So the effect sees the new value, but the screen hasn’t been updated yet.
  • Changes are batched. Like the redraw in Part 3, Angular doesn’t run the effect after each update. It marks the effect as needing a run, waits for your handler to finish, and runs it once. The effect never saw 1 or 2.
  • No change, no run. Do nothing caused a redraw, because it’s a click in the template. But count didn’t change, so the effect stayed quiet, and so did the computed.

So an effect suits keeping something outside Angular in step with your signals. You don’t choose the moment it runs.

Where you can create an effect

We created the effect in the constructor. You can also create it in a field initializer, the = ... part of a field:

private readonly logger = effect(() => console.log('effect sees', this.count()));

Both run while Angular is creating the component. Code that runs while Angular is creating something, like these two places, runs in what Angular calls an injection context. Inside it, effect() can find out which component it belongs to, so it can stop the effect when the component is destroyed. Outside it, for example in a click handler, effect() throws error NG0203. We’ll read that error in a worked example below.

You don’t need to keep the result unless you want to stop the effect early. That’s the next section.

Cleaning up: onCleanup and destroy

An effect’s function gets one argument, usually called onCleanup. You pass it a function, and Angular calls that function before the next run, or when the effect is destroyed. Use it to undo what the run started: clear a timer, remove a listener, cancel a request.

effect() also returns an EffectRef, an object with one method, destroy(), which stops the effect for good.

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

@Component({
  selector: 'app-root',
  template: `
    <p>{{ name() }}</p>
    <button (click)="next()">Next</button>
    <button (click)="stop()">Stop</button>
  `,
})
export class App {
  protected readonly name = signal('Ana');
  private readonly watcher = effect((onCleanup) => {
    const current = this.name();
    console.log('start', current);
    onCleanup(() => console.log('cleanup', current));
  });

  protected next() {
    this.name.update((n) => n + '!');
  }

  protected stop() {
    this.watcher.destroy();
  }
}

When the page loads, the console shows:

start Ana

Click Next. The cleanup for the old run comes first, then the new run:

cleanup Ana
start Ana!

Click Stop, then Next again. The console adds one line:

cleanup Ana!

destroy() ran the last cleanup. After that, the effect is gone, so the second Next changed name but started nothing. You rarely call destroy() yourself. An effect made in a component is destroyed with the component, and its last cleanup runs then.

Effects are rarely the answer

Here’s the most common misuse of an effect: keeping one signal in step with another. A product costs price, and shipping is always 5. The total is kept in a second signal, and an effect copies the sum into it.

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

@Component({
  selector: 'app-root',
  template: `
    <p>Price: {{ price() }}, total: {{ total() }}</p>
    <button (click)="raise()">Raise price</button>
  `,
})
export class App {
  protected readonly price = signal(10);
  protected readonly total = signal(0);

  constructor() {
    effect(() => {
      this.total.set(this.price() + 5);
    });
  }

  protected raise() {
    this.price.update((p) => p + 1);
    console.log('total right after:', this.total());
  }
}

Click Raise price, and the page shows:

Price: 11, total: 16
Raise price

But the console shows:

total right after: 15

Right after the price changed, total was still the old total. The effect hadn’t run yet: it runs later, as we saw. Any code that reads total between the change and the effect’s run gets a wrong answer. And total is a writable signal, so any method can set it to something that doesn’t match price at all.

Angular 22 doesn’t stop you. Setting a signal inside an effect is allowed, and it prints no warning. (Older versions required an allowSignalWrites option for this. The end of this part shows what Angular 22 says about it.) Being allowed doesn’t make it a good idea.

total is worked out from price. That’s exactly what computed is for:

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

@Component({
  selector: 'app-root',
  template: `
    <p>Price: {{ price() }}, total: {{ total() }}</p>
    <button (click)="raise()">Raise price</button>
  `,
})
export class App {
  protected readonly price = signal(10);
  protected readonly total = computed(() => this.price() + 5);

  protected raise() {
    this.price.update((p) => p + 1);
    console.log('total right after:', this.total());
  }
}

Click Raise price. The console now shows:

total right after: 16

A computed is never out of date when you read it, because reading it is what works out its value. And it can’t be set by mistake.

A quick test before you write an effect: is the thing I’m about to change a signal? If yes, you almost certainly want computed, or the linkedSignal we’ll meet below. Effects are for the world outside your signals: localStorage, the console, the page title, a chart or map library that knows nothing about Angular.

untracked(): read a signal without depending on it

An effect reruns when any signal it read changes. Sometimes you need a signal’s current value but don’t want its changes to trigger a run. untracked(fn) runs fn and doesn’t record the reads inside it.

Say you log each page a user views, with their name. A page change is a page view. A name change alone isn’t.

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="page.set(page() + 1)">Next page</button>
    <button (click)="user.set('Ben')">Ben</button>
  `,
})
export class App {
  protected readonly page = signal(1);
  protected readonly user = signal('Ana');

  constructor() {
    effect(() => {
      const p = this.page();
      const u = untracked(() => this.user());
      console.log(`page ${p}, user ${u}`);
    });
  }
}

When the page loads, the console shows:

page 1, user Ana

Click Ben. Nothing is logged:

Click Next page. The effect runs, and it reads the user’s name as it is now:

page 2, user Ben

The effect depends on page only. Take the untracked away, and Ben would log page 1, user Ben too.

untracked also helps when an effect calls a function you didn’t write. If that function reads signals, your effect depends on them too. Wrapping the call in untracked(() => ...) prevents that.

linkedSignal(): a value that resets when its source changes

Here’s a job neither tool fits. A list of fruit, and a selected fruit. The selection should start as the first fruit. The user can pick another. When the list is replaced, the old selection may not be in it any more, so it should go back to the first fruit of the new list.

A computed can’t be picked: you can’t set it. A plain signal doesn’t know when the list changes, so you’d need an effect to reset it, which is the misuse from above. linkedSignal is both at once: a writable signal whose value is worked out again whenever the signals it read change.

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

@Component({
  selector: 'app-root',
  template: `
    <p>Selected: {{ selected() }}</p>
    <button (click)="selected.set('pear')">Pick pear</button>
    <button (click)="fruit.set(['kiwi', 'plum'])">New list</button>
  `,
})
export class App {
  protected readonly fruit = signal(['apple', 'pear']);
  protected readonly selected = linkedSignal(() => this.fruit()[0]);
}

linkedSignal(() => this.fruit()[0]) reads like a computed: start with the first fruit. The page shows:

Selected: apple
Pick pearNew list

(The two buttons run together as Pick pearNew list because they sit on one line, as in Part 3.) Click Pick pear. selected is writable, so set works:

Selected: pear
Pick pearNew list

Click New list. fruit changed, so selected is worked out again, and your pick is replaced:

Selected: kiwi
Pick pearNew list

The animation follows those three steps. The dashed blue arrows mean “reads”, and the dashed red ones are clicks.

signal linkedSignal (writable) template fruit: [apple, pear] fruit: [kiwi, plum] selected: apple selected: pear selected: kiwi stale Selected: apple pear kiwi New list Pick pear fruit [apple, pear], selected apple, screen apple fruit [apple, pear], selected pear, screen pear fruit [kiwi, plum], selected stale, screen still pear fruit [kiwi, plum], selected kiwi, screen kiwi selected starts as the first fruit, like a computed Pick pear: selected.set('pear'). It's writable, like a signal New list: fruit changes, so selected is marked stale The render reads selected: it's worked out again, kiwi

A linkedSignal can be set by hand, but a change to its source sets it back.

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

  1. fruit holds apple and pear. selected read fruit and worked out its value: apple. The template read selected and shows apple.
  2. You click Pick pear, and the handler calls selected.set('pear'). A linkedSignal is writable, so it now holds pear, and the screen shows pear. fruit didn’t change.
  3. You click New list, and fruit becomes kiwi and plum. selected read fruit, so it’s marked stale, like a computed. Nothing is worked out yet, and the screen still shows pear.
  4. The render reads selected(). It sees that fruit changed, throws away the pear you picked, and works out its value again: kiwi.

Keeping the selection when it still makes sense

Resetting every time can be too much. If the new list still has pear in it, the user would expect pear to stay picked. For that, linkedSignal has a longer form. You give it a source, the signal to follow, and a computation, which gets the new source value and the previous state:

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

@Component({
  selector: 'app-root',
  template: `
    <p>Selected: {{ selected() }}</p>
    <button (click)="selected.set('pear')">Pick pear</button>
    <button (click)="fruit.set(['kiwi', 'pear'])">Pear list</button>
    <button (click)="fruit.set(['kiwi', 'plum'])">New list</button>
  `,
})
export class App {
  protected readonly fruit = signal(['apple', 'pear']);
  protected readonly selected = linkedSignal({
    source: this.fruit,
    computation: (list: string[], previous?: { value: string }) => {
      if (previous && list.includes(previous.value)) {
        return previous.value;
      }
      return list[0];
    },
  });
}

previous is undefined the first time. After that it’s an object whose value is what the linked signal held, including anything you set. (It also has source, the old source value; we don’t need it here.) The ? in previous?: is TypeScript for “this may be missing”.

Click Pick pear, then Pear list. The new list still has pear, so it stays:

Selected: pear
Pick pearPear listNew list

Click New list. Pear is gone, so the selection falls back to the first fruit:

Selected: kiwi
Pick pearPear listNew list

Custom equality: when “equal” means something else

Part 3 showed that a signal compares the old and new value with Object.is, and that a new object always counts as a change. You can give a signal your own test with the equal option. It’s a function that gets the old and the new value and returns true when they count as the same.

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

interface Point {
  x: number;
  y: number;
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="pos.set({ x: 1, y: 2 })">Same</button>
    <button (click)="pos.set({ x: 5, y: 2 })">Move</button>
  `,
})
export class App {
  protected readonly pos = signal<Point>(
    { x: 1, y: 2 },
    { equal: (a, b) => a.x === b.x && a.y === b.y },
  );

  constructor() {
    effect(() => console.log('at', this.pos().x, this.pos().y));
  }
}

Click Same, then Move. The console shows, since the page loaded:

at 1 2
at 5 2

Same set a new object, but equal said it matched the old one, so the signal didn’t notify anyone and the effect didn’t run. Without the equal option, Same would log at 1 2 again, because it’s a different object. computed and linkedSignal take the same equal option. You’ll rarely need it, but when an object is rebuilt often with the same contents, it saves the work that would follow.

Worked example: remember my settings

Here’s a real job for an effect. A small settings form keeps a name and a dark-mode switch. The settings should survive a page reload, so we keep them in localStorage, the browser’s small key-value store for each site. localStorage.setItem(key, text) saves text, and localStorage.getItem(key) gives it back, or null if there’s nothing saved.

The form is its own component, so we can close it and open it again:

// src/app/settings-form.ts
import { Component, computed, effect, signal } from '@angular/core';

interface Settings {
  name: string;
  dark: boolean;
}

const KEY = 'settings';

function loadSettings(): Settings {
  const saved = localStorage.getItem(KEY);
  return saved ? JSON.parse(saved) : { name: '', dark: false };
}

@Component({
  selector: 'app-settings-form',
  template: `
    <p>
      <label>Name <input [value]="settings().name" (input)="setName($event.target.value)" /></label>
    </p>
    <p>
      <label>
        <input
          type="checkbox"
          [checked]="settings().dark"
          (change)="setDark($event.target.checked)"
        />
        Dark mode
      </label>
    </p>
    <p>Hello, {{ greetingName() }}. Dark mode is {{ settings().dark ? 'on' : 'off' }}.</p>
  `,
})
export class SettingsForm {
  protected readonly settings = signal<Settings>(loadSettings());
  protected readonly greetingName = computed(() => this.settings().name || 'stranger');

  constructor() {
    effect(() => {
      const json = JSON.stringify(this.settings());
      localStorage.setItem(KEY, json);
      console.log('saved', json);
    });
  }

  protected setName(name: string) {
    this.settings.update((s) => ({ ...s, name }));
  }

  protected setDark(dark: boolean) {
    this.settings.update((s) => ({ ...s, dark }));
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { SettingsForm } from './settings-form';

@Component({
  selector: 'app-root',
  imports: [SettingsForm],
  template: `
    <button (click)="open.set(!open())">Open or close</button>
    @if (open()) {
      <app-settings-form />
    }
  `,
})
export class App {
  protected readonly open = signal(true);
}

How it fits together:

  • loadSettings() runs once, when the component is created, to give the signal its starting value. JSON.parse turns the saved text back into an object. With nothing saved, we start with an empty name and dark mode off.
  • The effect reads settings(), so it runs whenever the settings change. It writes them to storage. It changes nothing inside Angular, which is what makes it a good effect.
  • greetingName uses ||, JavaScript’s “or”: with an empty name, it gives 'stranger'.
  • setName and setDark make a new object with { ...s, name }, as Part 3 taught: copy every property of s, then replace name.
  • $event.target.value and $event.target.checked work because Angular 22 types $event.target on an <input> as HTMLInputElement (Part 2).

When the page loads, the effect runs once and saves the defaults:

saved {"name":"","dark":false}

Type Ana into Name and tick Dark mode. The page shows:

Open or close
Name
Dark mode
Hello, Ana. Dark mode is on.

and the console shows a save for each change:

saved {"name":"Ana","dark":false}
saved {"name":"Ana","dark":true}

Now click Open or close twice. The first click destroys the form, and its effect with it. The second makes a brand-new SettingsForm, whose signal starts from loadSettings(). The page shows:

Open or close
Name
Dark mode
Hello, Ana. Dark mode is on.

The new form found Ana and dark mode in storage. Its effect ran once, as every new effect does, and saved the same settings again:

saved {"name":"Ana","dark":true}

A page reload works the same way: the new page creates a new SettingsForm, which reads the same storage. Try it in your own project: type a name, press F5, and the name is still there.

The effect doesn’t work out the greeting or set any signal. Its one job is talking to something outside Angular.

Worked example: a master–detail list

A master–detail page has a list on one side and the details of the selected item on the other. Here the list of books can be filtered by category. The selection is a linkedSignal that follows the filtered list: it keeps the selected book if the book is still shown, and otherwise picks the first one.

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

type Category = 'all' | 'fiction' | 'science';

interface Book {
  id: number;
  title: string;
  author: string;
  category: 'fiction' | 'science';
}

const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', category: 'fiction' },
  { id: 2, title: 'Cosmos', author: 'Carl Sagan', category: 'science' },
  { id: 3, title: 'Emma', author: 'Jane Austen', category: 'fiction' },
  { id: 4, title: 'The Gene', author: 'Siddhartha Mukherjee', category: 'science' },
];

@Component({
  selector: 'app-root',
  template: `
    <p>
      <button (click)="category.set('all')">All</button>
      <button (click)="category.set('fiction')">Fiction</button>
      <button (click)="category.set('science')">Science</button>
    </p>
    <ul>
      @for (book of visible(); track book.id) {
        <li>
          <button (click)="selected.set(book)">{{ book.title }}</button>
        </li>
      }
    </ul>
    @if (selected(); as book) {
      <p>Selected: {{ book.title }} by {{ book.author }}</p>
    }
  `,
})
export class App {
  protected readonly category = signal<Category>('all');
  protected readonly visible = computed(() =>
    BOOKS.filter((b) => this.category() === 'all' || b.category === this.category()),
  );
  protected readonly selected = linkedSignal({
    source: this.visible,
    computation: (list: Book[], previous?: { value: Book | undefined }) =>
      list.find((b) => b.id === previous?.value?.id) ?? list[0],
  });
}

Some things to notice:

  • type Category = 'all' | 'fiction' | 'science' is a union type, as in Part 7: a Category is one of those three strings, and nothing else. category.set('poetry') wouldn’t build.
  • visible is a computed. It’s derived from category, so it can’t be anything else.
  • selected‘s source is visible, a computed. A source can be any signal.
  • previous?.value?.id uses optional chaining, ?.: if previous or its value is missing, the whole thing is undefined instead of an error. So the first time, find finds nothing, and ?? falls back to list[0]. (?? means “use the right side if the left is null or undefined“.)
  • @if (selected(); as book) from Part 4 shows the details only when there’s a book.

When the page loads, the page shows:

AllFictionScience
Dune
Cosmos
Emma
The Gene
Selected: Dune by Frank Herbert

Click Emma, then Fiction. Emma is fiction, so the filter keeps it and the selection stays:

AllFictionScience
Dune
Emma
Selected: Emma by Jane Austen

Click Science. Emma isn’t in the list any more, so the selection moves to the first science book:

AllFictionScience
Cosmos
The Gene
Selected: Cosmos by Carl Sagan

Click All. Cosmos is still shown, so it stays selected:

AllFictionScience
Dune
Cosmos
Emma
The Gene
Selected: Cosmos by Carl Sagan

There’s no effect and no reset code in the click handlers. The rule “keep it if it’s still shown” lives next to the signal it describes.

Worked example: effect() in a click handler, NG0203

Say you want a Start logging button: after it’s clicked, every change to the count is logged. A first try creates the effect when the button is clicked:

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

@Component({
  selector: 'app-root',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="count.set(count() + 1)">Add one</button>
    <button (click)="startLogging()">Start logging</button>
  `,
})
export class App {
  protected readonly count = signal(0);

  protected startLogging() {
    effect(() => console.log('count is', this.count()));
  }
}

It builds. Click Start logging, and the console shows an error, which starts like this:

ERROR RuntimeError: NG0203: effect() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://v22.angular.dev/errors/NG0203
    at assertInInjectionContext (...)
    at effect (...)
    at _App.startLogging (...)

Read it piece by piece:

  • NG0203 is Angular’s code for this error. The link at the end of the first line explains it on angular.dev.
  • effect() can only be used within an injection context names the rule we met earlier. A click handler runs long after the component was created, so it isn’t in one.
  • such as a constructor, ... a field initializer lists the places that are.
  • The lines starting with at are the stack trace: which function called which, newest first. effect was called from startLogging. That’s the line to fix. (The real trace has file names and line numbers where we wrote ....)

Unlike Part 3’s build errors, this one shows up only when the code runs. The page keeps working, but no effect was made.

The fix is to create the effect in the constructor, where it’s allowed, and let a signal switch the logging on:

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

@Component({
  selector: 'app-root',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="count.set(count() + 1)">Add one</button>
    <button (click)="logging.set(true)">Start logging</button>
  `,
})
export class App {
  protected readonly count = signal(0);
  protected readonly logging = signal(false);

  constructor() {
    effect(() => {
      if (!this.logging()) {
        return;
      }
      console.log('count is', this.count());
    });
  }
}

Click Add one, Start logging, then Add one again. The console shows:

count is 1
count is 2

The first Add one logged nothing. While logging was false, the effect returned before reading count, so it didn’t depend on count at all, just as Part 3’s computed only followed the signals it read. Start logging changed logging, the effect ran, and this time it read count too.

There’s another way out: effect() takes an injector option, which lets you create it anywhere if you hand it the component’s injector. That needs inject(), which Part 13 covers. Most of the time, the signal switch above is simpler.

In older code

Before effect and linkedSignal, the same jobs were done in other ways. To reset a selection when an input changed, a component had an ngOnChanges(changes) method, which Angular called with the old and new input values, and the code reset a field by hand. To save a form as it changed, code called .subscribe() on an RxJS stream such as a form’s valueChanges, and had to unsubscribe when the component was destroyed. Part 20 covers RxJS.

Older effect code may also pass { allowSignalWrites: true }, from the versions where an effect wasn’t allowed to set signals:

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

@Component({
  selector: 'app-root',
  template: `<p>{{ count() }}</p>`,
})
export class App {
  protected readonly count = signal(0);

  constructor() {
    effect(() => console.log('count', this.count()), { allowSignalWrites: true });
  }
}

It still builds, but the console shows a warning:

The 'allowSignalWrites' flag is deprecated and no longer impacts effect() (writes are always allowed)

Delete the option. Writes are allowed without it.

Best practices

  • Reach for computed first, linkedSignal second, and effect last. A computed can’t drift out of step, and a linkedSignal covers “derived, but the user can change it”. Both replace an effect that sets a signal.
  • Use effects for things outside Angular’s signals: localStorage, logging, the page title, a non-Angular library. That replaces subscribing to changes by hand and unsubscribing later.
  • Create effects in the constructor or a field initializer. They’re tied to the component and destroyed with it, so you don’t need to keep the EffectRef or clean up yourself.
  • Undo what an effect starts with onCleanup. A timer or a listener from the last run should end before the next run starts. That replaces keeping the old handle in a field and clearing it by hand.
  • Use untracked for values you need but shouldn’t react to, and around calls into code you didn’t write. It keeps an effect’s dependencies to the ones you meant.

Tips and traps

  • An effect that sets a signal. It works on screen, so it looks fine, but code that reads the signal right after a change gets the old value, and any method can set it out of step. Use computed or linkedSignal.
  • Creating an effect in a click handler. The console shows NG0203: effect() can only be used within an injection context, and nothing is logged or saved. Create it in the constructor and gate it with a signal.
  • Expecting an effect to run straight away. It runs after your handler finishes, once, with the final values. If you need a value right after a change, read a computed instead.
  • Reading the page inside an effect. A component’s effect runs before its template is checked, so the screen still shows the old values. Part 10 covers afterRenderEffect, which runs after the screen is updated.
  • An effect that depends on more than you meant. Every signal read inside it is a dependency, including reads in functions it calls. Wrap the ones you don’t want in untracked.
  • A linkedSignal that forgets the user’s pick. The short form resets on every source change. If the pick should survive when it still makes sense, use the source and computation form and check previous.

Use computed for values, linkedSignal for values the user can change, and effect only to reach outside Angular.

Exercises

Exercise 1. This page keeps fullName in step with an effect. It shows the right name, but it’s the misuse from this part. Rewrite it without an effect, and check that Ben still changes the name.

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

@Component({
  selector: 'app-root',
  template: `
    <p>{{ fullName() }}</p>
    <button (click)="first.set('Ben')">Ben</button>
  `,
})
export class App {
  protected readonly first = signal('Ana');
  protected readonly last = signal('Kim');
  protected readonly fullName = signal('');

  constructor() {
    effect(() => this.fullName.set(`${this.first()} ${this.last()}`));
  }
}
Ana Kim
Ben

Exercise 2. Without running it, what does the console show after the page loads and you click B, A, then B?

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="a.set(a() + 1)">A</button>
    <button (click)="b.set(b() + 1)">B</button>
  `,
})
export class App {
  protected readonly a = signal(0);
  protected readonly b = signal(0);

  constructor() {
    effect(() => console.log(`a ${this.a()}, b ${untracked(() => this.b())}`));
  }
}

Exercise 3. Write a page with a product signal that starts as 'Tea', buttons Tea and Cake that set it, and a quantity that starts at 1. A +1 button adds one to the quantity. Picking a product sets the quantity back to 1. The page should show Tea × 3 after clicking +1 twice, and Cake × 1 after then clicking Cake. Use linkedSignal, not an effect.

Answers

1. fullName is worked out from first and last, so it’s a computed:

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

@Component({
  selector: 'app-root',
  template: `
    <p>{{ fullName() }}</p>
    <button (click)="first.set('Ben')">Ben</button>
  `,
})
export class App {
  protected readonly first = signal('Ana');
  protected readonly last = signal('Kim');
  protected readonly fullName = computed(() => `${this.first()} ${this.last()}`);
}

Click Ben. The page shows:

Ben Kim
Ben

2. Two lines. The effect runs once at the start. It reads b inside untracked, so it depends on a only. The first B changes b but runs nothing. A runs the effect, which reads b as it is now, 1. The second B runs nothing again.

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

@Component({
  selector: 'app-root',
  template: `
    <button (click)="a.set(a() + 1)">A</button>
    <button (click)="b.set(b() + 1)">B</button>
  `,
})
export class App {
  protected readonly a = signal(0);
  protected readonly b = signal(0);

  constructor() {
    effect(() => console.log(`a ${this.a()}, b ${untracked(() => this.b())}`));
  }
}
a 0, b 0
a 1, b 1

3. The quantity follows product, and the computation ignores the product and returns 1, so any product change resets it:

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

@Component({
  selector: 'app-root',
  template: `
    <p>{{ product() }} × {{ quantity() }}</p>
    <button (click)="product.set('Tea')">Tea</button>
    <button (click)="product.set('Cake')">Cake</button>
    <button (click)="quantity.update((q) => q + 1)">+1</button>
  `,
})
export class App {
  protected readonly product = signal('Tea');
  protected readonly quantity = linkedSignal({ source: this.product, computation: () => 1 });
}

Click +1 twice. The page shows:

Tea × 3
TeaCake+1

Click Cake. The page shows:

Cake × 1
TeaCake+1

Click +1, then Cake again. The page shows:

Cake × 2
TeaCake+1

Picking the product that’s already picked doesn’t reset the quantity. Setting a signal to the value it already has changes nothing, as in Part 3, so the linked signal’s source never changed.

What’s next

So far a component’s template has been all its own. In Part 9, we’ll let a parent pass whole pieces of template into a child with ng-content, named slots and ng-template.

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.