Demo
HTML
TS
CSS
🧮 Signal Example 4: Computed Signal
âš¡ Explore computed signals in Angular! This example shows how you can derive new, reactive values from existing signals, keeping your UI in sync with minimal code.
🧮 Computed Signal
Count: 0
Computed count = 0 + 2 → 2
âš¡ Deep Dive: Computed Signals in Angular
Computed signals are a powerful feature in Angular’s signal system. They let you create new signals whose values are automatically derived from other signals. This enables you to build complex, reactive UIs with very little code.
A computed signal is a function that returns a value based on one or more other signals. Whenever any of those signals change, the computed signal automatically recalculates and updates the UI.
How This Example Works
- Base Signal: The main counter value is stored in a signal, e.g.
count = signal(0); - Computed Signal: A new signal is created using
computed(() => count() + 2). This signal,doubleCount, always reflectscount + 2. - Reactive UI: The template uses
2to display the computed value. Whenevercount()changes,doubleCount()updates automatically. - No Manual Updates: You never have to set the computed signal yourself. Angular tracks dependencies and updates everything for you.
- Chaining: Computed signals can depend on other computed signals, enabling advanced reactive logic.
Why Use Computed Signals?
- Declarative Logic: Express relationships between values directly in your code.
- Automatic Updates: No need to manually synchronize derived values.
- Performance: Only the parts of the UI that depend on the computed signal are updated.
- Maintainability: Less boilerplate and fewer bugs from out-of-sync state.
★Computed signals make it easy to build complex, reactive UIs that stay perfectly in sync—automatically!
