8. Angular Signals
signal(), computed(), effect(), and the bridge between synchronous reactivity and RxJS
Observables are powerful — but they're also complex. For synchronous, component-local state like "is this dropdown open?" or "what's the current count?", the full Observable machinery is overkill. Angular Signals are a simpler reactivity primitive designed for exactly this use case: synchronous state that Angular can track automatically, without Zone.js.
What Is a Signal?
A Signal is a wrapper around a value that notifies consumers when that value changes. Unlike an Observable, a Signal always has a current value, is synchronous, and doesn't require subscription management.
import { signal } from '@angular/core';
const count = signal(0); // create with initial value
console.log(count()); // read: 0
count.set(5); // write: replace the value
console.log(count()); // read: 5
count.update(n => n + 1); // write: derive from current value
console.log(count()); // read: 6
Three things to notice:
- Reading a Signal is a function call —
count(), notcount - Writing uses
.set()(replace) or.update()(derive from current) - There's no
subscribe, nounsubscribe, nopipe— just get and set
Signals in templates
When you read a Signal in a template, Angular automatically tracks the dependency. When the Signal changes, Angular knows exactly which template binding needs updating — no dirty-checking required.
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ count() }}</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`
})
export class CounterComponent {
count = signal(0);
increment() {
this.count.update(n => n + 1);
}
reset() {
this.count.set(0);
}
}
No BehaviorSubject, no async pipe, no OnDestroy cleanup. The Signal is the state, and Angular knows when it changes.
Computed Signals
A computed() Signal derives its value from other Signals. It's like a spreadsheet formula — when any input Signal changes, the computed value is recalculated automatically.
import { signal, computed } from '@angular/core';
const firstName = signal('Ada');
const lastName = signal('Lovelace');
const fullName = computed(() => `${firstName()} ${lastName()}`);
console.log(fullName()); // "Ada Lovelace"
firstName.set('Grace');
console.log(fullName()); // "Grace Lovelace"
Key properties of computed()
- Lazy: the computation runs only when the value is read
- Memoized: if no input Signals changed, the cached value is returned
- Read-only: you can't
.set()a computed Signal - Glitch-free: Angular ensures computed values are consistent — you'll never see a "half-updated" state
@Component({
template: `
<input (input)="onSearch($event)">
<p>Showing {{ filteredCount() }} of {{ users().length }} users</p>
<div *ngFor="let user of filteredUsers()">{{ user.name }}</div>
`
})
export class UserListComponent {
users = signal<User[]>([]);
searchTerm = signal('');
filteredUsers = computed(() =>
this.users().filter(u =>
u.name.toLowerCase().includes(this.searchTerm().toLowerCase())
)
);
filteredCount = computed(() => this.filteredUsers().length);
onSearch(event: Event) {
this.searchTerm.set((event.target as HTMLInputElement).value);
}
}
This builds a reactive chain: users + searchTerm -> filteredUsers -> filteredCount. Change either input Signal, and all dependent computed Signals update automatically.
Effects
An effect() runs a side effect whenever any Signal it reads changes. Effects are for doing things in response to Signal changes — logging, localStorage syncing, imperative DOM manipulation.
import { signal, effect } from '@angular/core';
@Component({ /* ... */ })
export class ThemeComponent {
theme = signal<'light' | 'dark'>('light');
constructor() {
effect(() => {
// Runs whenever this.theme() changes
document.body.setAttribute('data-theme', this.theme());
console.log('Theme changed to:', this.theme());
});
}
toggle() {
this.theme.update(t => t === 'light' ? 'dark' : 'light');
}
}
Effect rules
- Automatic tracking: the effect tracks whichever Signals are read inside its callback
- Runs at least once: effects execute during creation to establish dependencies
- Cleaned up automatically: when the component is destroyed, the effect is disposed
- Cannot write to Signals by default: effects are for side effects, not state derivation. Use
computed()for derived state
// This will warn at runtime:
effect(() => {
this.derived.set(this.source() * 2); // Don't do this!
});
// Use computed instead:
derived = computed(() => this.source() * 2);
If you genuinely need to write to a Signal from an effect (e.g., synchronizing with external state), opt in explicitly:
effect(() => {
this.externalState.set(this.localState());
}, { allowSignalWrites: true });
Signal Inputs (Angular 17.1+)
Signal-based inputs replace the @Input() decorator with a Signal that Angular populates automatically:
import { Component, input } from '@angular/core';
@Component({
selector: 'app-user-card',
template: `
<div class="card" [class.admin]="isAdmin()">
<h3>{{ user().name }}</h3>
<p>{{ user().email }}</p>
<span>{{ roleBadge() }}</span>
</div>
`
})
export class UserCardComponent {
// Required input
user = input.required<User>();
// Optional input with default
showEmail = input(true);
// Computed from input signals
isAdmin = computed(() => this.user().role === 'admin');
roleBadge = computed(() =>
this.isAdmin() ? 'Admin' : 'Member'
);
}
Signal inputs are:
- Read-only — the parent sets the value, the child can't modify it
- Type-safe —
input.required<User>()errors at compile time if the parent forgets to provide it - Composable — use them directly in
computed()chains
input() vs @Input()
| Feature | @Input() |
input() |
|---|---|---|
| Type | Property | Signal |
| Access | this.user |
this.user() |
| Derived state | Needs ngOnChanges or setter |
Use computed() directly |
| Required | @Input({ required: true }) |
input.required<T>() |
| Transform | @Input({ transform }) |
input(default, { transform }) |
Signal Queries (Angular 17.2+)
viewChild(), viewChildren(), contentChild(), and contentChildren() are Signal-based replacements for the @ViewChild / @ContentChild decorators:
import { Component, viewChild, viewChildren, ElementRef } from '@angular/core';
@Component({
selector: 'app-form',
template: `
<input #nameInput>
<input #emailInput>
<div #container></div>
`
})
export class FormComponent {
nameInput = viewChild.required<ElementRef>('nameInput');
container = viewChild<ElementRef>('container');
allInputs = viewChildren<ElementRef>('nameInput, emailInput');
focusName() {
this.nameInput().nativeElement.focus();
}
inputCount = computed(() => this.allInputs().length);
}
Because these are Signals, you can use them in computed() and effect() — something that was awkward with the decorator-based queries.
Model Inputs: Two-Way Binding with Signals
model() creates a Signal input that supports two-way binding — the child can both read and write the value:
import { Component, model } from '@angular/core';
@Component({
selector: 'app-rating',
template: `
<div class="stars">
@for (star of stars(); track star) {
<span
[class.filled]="star <= value()"
(click)="value.set(star)">
★
</span>
}
</div>
`
})
export class RatingComponent {
value = model(0); // two-way bindable Signal
max = input(5); // read-only input Signal
stars = computed(() =>
Array.from({ length: this.max() }, (_, i) => i + 1)
);
}
Used with two-way binding syntax in the parent:
<app-rating [(value)]="userRating" [max]="10"></app-rating>
Bridging Signals and RxJS
Signals and Observables serve different purposes. Use the interop functions to bridge them.
toSignal() — Observable to Signal
import { toSignal } from '@angular/core/rxjs-interop';
@Component({
template: `
<p>Route: {{ currentRoute() }}</p>
<div *ngFor="let user of users()">{{ user.name }}</div>
`
})
export class UserPageComponent {
private route = inject(ActivatedRoute);
private userService = inject(UserService);
// Observable -> Signal (requires initial value or { requireSync: true })
currentRoute = toSignal(
this.route.paramMap.pipe(map(p => p.get('id'))),
{ initialValue: null }
);
users = toSignal(this.userService.getAll(), { initialValue: [] });
}
toSignal() subscribes to the Observable, updates the Signal on each emission, and unsubscribes automatically when the component is destroyed. No async pipe, no takeUntilDestroyed().
toObservable() — Signal to Observable
import { toObservable } from '@angular/core/rxjs-interop';
@Component({ /* ... */ })
export class SearchComponent {
searchTerm = signal('');
// Signal -> Observable, then use RxJS operators
results$ = toObservable(this.searchTerm).pipe(
debounceTime(300),
distinctUntilChanged(),
filter(term => term.length >= 2),
switchMap(term => inject(SearchService).search(term))
);
// Convert back to Signal for the template
results = toSignal(this.results$, { initialValue: [] });
}
This is the best of both worlds: use Signals for synchronous state and template binding, use RxJS for async operations and complex stream logic.
When to use Signals vs Observables
| Use Signals when... | Use Observables when... |
|---|---|
| State is synchronous | Values arrive asynchronously |
| You just need a current value | You need operators (debounce, retry, combine) |
| Component-local state | Cross-cutting async flows |
Template binding (replacing async) | HTTP calls, WebSockets, route changes |
| Derived/computed state | Complex event coordination |
They're not competing — they're complementary. Use toSignal() and toObservable() to bridge them.
Signals and Change Detection
Signals fundamentally change how change detection works. Instead of Zone.js watching everything and checking everything, Signals give Angular precise knowledge of what changed.
With Signals:
- Angular knows exactly which template bindings read which Signals
- When a Signal changes, Angular marks only the affected bindings as dirty
- No Zone.js is needed — Signals are the notification mechanism
This is the foundation of zoneless Angular. A fully signal-based component doesn't need Zone.js at all:
@Component({
selector: 'app-todo',
template: `
<input #input>
<button (click)="add(input.value); input.value = ''">Add</button>
<ul>
@for (todo of filteredTodos(); track todo.id) {
<li [class.done]="todo.done" (click)="toggle(todo)">
{{ todo.text }}
</li>
}
</ul>
<p>{{ activeCount() }} remaining</p>
`
})
export class TodoComponent {
todos = signal<Todo[]>([]);
filter = signal<'all' | 'active' | 'done'>('all');
filteredTodos = computed(() => {
const f = this.filter();
return this.todos().filter(t =>
f === 'all' ? true : f === 'active' ? !t.done : t.done
);
});
activeCount = computed(() =>
this.todos().filter(t => !t.done).length
);
add(text: string) {
this.todos.update(list => [
...list,
{ id: Date.now(), text, done: false }
]);
}
toggle(todo: Todo) {
this.todos.update(list =>
list.map(t => t.id === todo.id ? { ...t, done: !t.done } : t)
);
}
}
Every piece of state is a Signal or computed Signal. Angular tracks the dependencies automatically and updates only the bindings that changed.
The linkedSignal (Angular 19+)
linkedSignal creates a writable Signal that resets when a source Signal changes — useful for "local state that depends on an input":
import { linkedSignal, input, computed } from '@angular/core';
@Component({
selector: 'app-paginated-list',
template: `
<div *ngFor="let item of pageItems()">{{ item.name }}</div>
<button (click)="prevPage()" [disabled]="currentPage() <= 0">Prev</button>
<span>Page {{ currentPage() + 1 }} of {{ totalPages() }}</span>
<button (click)="nextPage()" [disabled]="currentPage() >= totalPages() - 1">Next</button>
`
})
export class PaginatedListComponent {
items = input.required<Item[]>();
pageSize = input(10);
// Resets to 0 whenever items() changes
currentPage = linkedSignal(() => {
this.items(); // track this dependency
return 0; // reset value
});
totalPages = computed(() =>
Math.ceil(this.items().length / this.pageSize())
);
pageItems = computed(() => {
const start = this.currentPage() * this.pageSize();
return this.items().slice(start, start + this.pageSize());
});
nextPage() { this.currentPage.update(p => p + 1); }
prevPage() { this.currentPage.update(p => p - 1); }
}
Without linkedSignal, you'd need ngOnChanges or an effect to reset the page when the item list changes.
Resource API (Angular 19+)
The resource() function combines Signals with async data fetching — think of it as toSignal() for data that depends on other Signals:
import { resource, signal } from '@angular/core';
@Component({
template: `
@if (userResource.isLoading()) {
<p>Loading...</p>
}
@if (userResource.error()) {
<p class="error">{{ userResource.error() }}</p>
}
@if (userResource.value(); as user) {
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
}
`
})
export class UserDetailComponent {
userId = input.required<number>();
userResource = resource({
request: () => this.userId(),
loader: ({ request: id }) =>
fetch(`/api/users/${id}`).then(r => r.json())
});
}
The resource automatically re-fetches when userId changes, tracks loading/error states, and exposes everything as Signals. No manual subscription management.
Try It Yourself -- Signal Dependency Graph
Build a reactive graph by creating Signals and computed values. Change a Signal's value and watch the updates propagate through the dependency chain. Notice how computed values are lazy -- they only recalculate when read after a dependency changes.
Migration Path
You don't have to rewrite your app. Signals and Observables coexist. A practical migration:
- New components: use Signals for local state,
toSignal()for service Observables - Existing OnPush components: gradually replace
BehaviorSubject+asyncwith Signals - Services: keep using Observables for HTTP, WebSockets, and complex async logic
- NgRx: use
selectSignal()instead ofselect()for Signal-based store access - Zoneless: once all components use Signals or OnPush + async, enable zoneless mode
What's Next
Now you know Signals — but your codebase is full of Observables. How do you decide which to use when? How do you migrate incrementally without rewriting everything? The next article is a practical bridge guide covering the decision framework, every interop pattern (toSignal, toObservable, the sandwich pattern), and a step-by-step migration playbook for real Angular code.