Sub topic 2
Dependencies, Effects, and Angular Signal Logic
Assume you know basic TypeScript, Angular components, templates, dependency injection, and change detection. This chapter focuses on how Angular discovers signal dependencies while code runs.
Dependencies are discovered at run time
A computed() signal tracks only the signals read during its latest evaluation. Dependencies can therefore change when a condition changes.
import { computed, signal } from '@angular/core';
const showDetails = signal(false);
const name = signal('Ada');
const details = signal('Mathematician');
const label = computed(() =>
showDetails() ? `${name()} - ${details()}` : name()
);
console.log(label()); // Ada
details.set('Programmer'); // No invalidation while details is not read
showDetails.set(true);
console.log(label()); // Ada - ProgrammerWhile showDetails() is false, label depends on showDetails and name, but not details. After showDetails becomes true and label() is read again, details becomes a dependency.
Running side effects with effect()
An effect() runs at least once and runs again when a tracked signal changes. Use it for work outside the signal graph, such as logging, browser APIs, or synchronizing an external service.
import { Component, effect, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `<button (click)="increment()">{{ count() }}</button>`,
})
export class CounterComponent {
count = signal(0);
constructor() {
effect(() => {
console.log('count:', this.count());
});
}
increment() {
this.count.update((value) => value + 1);
}
}The constructor provides an injection context, so Angular can manage this effect with the component. Effects run asynchronously during change detection.
Computed, effect, or event handler?
Use the operation that matches the kind of work:
| Operation | Best use |
|---|---|
| `computed()` | Calculate read-only state from other signals |
| `effect()` | Synchronize with an external system |
| Event handler | Respond directly to a user action |
For example, calculate total with computed(), save it to storage with an effect(), and change quantity in a click handler.
Exercise
If a computed function reads details only when showDetails() is true, will changing details always invalidate it?
Show answer
No. details is tracked only during evaluations where showDetails() is true.