Sub topic 2
A quick refresher on signals
This chapter covers the parts of Angular signals you need before working with input() and output(). It assumes you know TypeScript classes and generics, standalone components, and basic template syntax. It also assumes you have seen a signal read by calling it. If you use signals daily, skim the summary table near the end and go on to the next chapter.
Why signals come first
A signal input created with input() is a signal. The InputSignal you get back is a read-only signal that Angular updates from the parent's bindings. You read it with name(), derive values from it with computed(), and react to it with effect(). If any of those steps is unfamiliar, the input examples later in this tutorial will be harder to follow.
What a signal is
A signal is a wrapper around a value that tells Angular when the value changes. You create a writable signal with signal() and read it by calling it like a function.
import { signal } from '@angular/core';
const count = signal(0);
console.log(count()); // 0
count.set(5);
console.log(count()); // 5
count.update((value) => value + 1);
console.log(count()); // 6There are three operations:
- Calling
count()reads the current value. set(newValue)replaces the value.update(fn)computes the new value from the old one.
The call matters because it is how Angular learns who depends on the signal. When a template or a computed value calls count(), Angular records that dependency. When the value changes, Angular knows what to refresh.
Signals hold values, not mutations
Angular decides whether a signal changed by comparing the old and new values with Object.is. If you mutate an array or object in place, the reference stays the same and dependents are not notified.
import { signal } from '@angular/core';
const items = signal<string[]>(['a']);
// Wrong: the array reference is unchanged, so nothing is notified.
items().push('b');
// Right: create a new array.
items.update((list) => [...list, 'b']);Treat signal values as immutable and replace them with new objects or arrays. This habit also applies to inputs. A parent that passes a mutated object instead of a new one gives the child no change to react to.
Computed signals
computed() creates a signal whose value is derived from other signals. You give it a function, and Angular tracks which signals that function reads.
import { computed, signal } from '@angular/core';
const price = signal(10);
const quantity = signal(3);
const total = computed(() => price() * quantity());
console.log(total()); // 30
quantity.set(4);
console.log(total()); // 40A computed signal has three properties that matter for the rest of the tutorial.
- It is read-only. It has no
set()orupdate(). Its value always comes from its function. - It is lazy. The function does not run until something reads the value for the first time.
- It is memoized. Angular caches the result and recomputes only when a signal it read has changed. Reading
total()ten times without changes runs the function once.
Dependencies are tracked dynamically. Only the signals actually read during the latest run count as dependencies.
import { computed, signal } from '@angular/core';
const showName = signal(true);
const name = signal('Ada');
const label = computed(() => (showName() ? name() : 'Hidden'));While showName() is false, label does not depend on name, so changing name does not recompute it.
Effects
effect() runs a function for its side effects, and it runs again whenever a signal it reads changes. Use it for work outside the signal graph, such as logging, writing to localStorage, or calling a non-Angular library.
The next component combines all three tools: a writable signal, a computed signal, and an effect.
import { Component, computed, effect, signal } from '@angular/core';
@Component({
selector: 'app-cart',
template: `
<p>Items: {{ items().length }}</p>
<p>Total: {{ total() }}</p>
<button (click)="add(5)">Add item</button>
`,
})
export class Cart {
items = signal<number[]>([]);
total = computed(() => this.items().reduce((sum, price) => sum + price, 0));
constructor() {
effect(() => {
console.log(`Cart total is now ${this.total()}`);
});
}
add(price: number) {
this.items.update((list) => [...list, price]);
}
}The template reads items() and total(), so Angular refreshes those parts of the view when the signals change. The effect logs once after the component first renders and again after every click.
Three facts about effects cause most of the confusion:
- Effects need an injection context. Create them in a constructor or a field initializer, as above. Calling
effect()from an ordinary method throws an error unless you pass aninjectoroption. - Effects run asynchronously. They are scheduled by Angular, not run in the middle of your
set()call. Do not expect the effect to have run on the line after you update a signal. - Effects are for side effects, not for deriving state. If you are about to write one signal inside an effect to mirror another, use
computed()instead. It is simpler and avoids extra change passes.
Reading without tracking
Sometimes an effect or computed function needs a value but should not re-run when that value changes. Wrap the read in untracked().
import { Component, effect, signal, untracked } from '@angular/core';
@Component({
selector: 'app-logger',
template: `<button (click)="query.set('angular')">Search</button>`,
})
export class Logger {
query = signal('');
pageSize = signal(20);
constructor() {
effect(() => {
const q = this.query();
const size = untracked(() => this.pageSize());
console.log(`Searching "${q}" with page size ${size}`);
});
}
}This effect re-runs when query changes. It does not re-run when pageSize changes.
How the pieces connect
The following diagram shows the direction of data. Writable signals sit at the source. Computed signals and effects read from them. The template reads from both.
Values move in one direction, from writable sources toward consumers. A signal input fits into this picture as a source that Angular writes on your behalf. You cannot write it yourself.
Summary of the tools
| Tool | Writable by you | Purpose | Runs when |
|---|---|---|---|
| `signal()` | Yes, with `set()` and `update()` | Hold state | Never runs; it is a value |
| `computed()` | No | Derive a value from other signals | On read, if a dependency changed |
| `effect()` | Not applicable | Run side effects | After a dependency changes, scheduled by Angular |
| `input()` | No, only the parent changes it | Receive a value from a parent | Updated by Angular when the binding changes |
Common errors
- Forgetting the parentheses. Writing
{{ count }}in a template shows the signal object, not its value. In TypeScript,if (count > 3)compares a function to a number and fails to compile for typed signals. Always writecount(). - Calling
set()on a computed signal. Computed signals have no write methods, and TypeScript reports an error. Change the signals the computed value reads instead. - Mutating in place.
items().push(x)does not notify anyone. Useupdate()with a new array. - Creating an effect outside an injection context. Move it to the constructor or a field initializer.
- Reading a signal inside
computed()through a non-signal path. If the function reads a plain property such asthis.countinstead ofthis.count(), it is not tracked and the computed value goes stale.
What carries forward
Three ideas from this chapter matter in the next chapters:
- You read a signal by calling it, and that call registers a dependency.
- A computed signal is read-only, cached, and recomputed only when a dependency changes.
- Signal values should be replaced, not mutated.
A signal input behaves like a read-only signal, so computed() over an input works exactly like the examples above. Angular does the writing from the parent's binding, and your component only reads.
Exercise
A component has first = signal('Grace') and last = signal('Hopper'). Write a fullName field that stays up to date when either signal changes. Then explain what happens when a template reads fullName() three times in a row without either signal changing.
Show answer
Declare fullName = computed(() => ${this.first()} ${this.last()});. The first read runs the function and caches the result. The next two reads return the cached value without running the function again, because neither dependency has changed. If you later call this.first.set('Ada'), the next read of fullName() recomputes and returns "Ada Hopper".
Exercise
This code is meant to add a tag to a signal holding an array, but the template never updates. Name the problem and give the fix. tags = signal<string[]>(['angular']); addTag(tag: string) { this.tags().push(tag); }
Show answer
push() mutates the existing array, so the signal's value keeps the same reference and Angular sees no change. Replace the array instead: this.tags.update((list) => [...list, tag]);.