⏱️ Signal Example 2: Auto Increment Counter

Discover how Angular Signals can power an auto-incrementing counter! This example shows a counter that increases by 1 every second, updating the UI reactively and efficiently.

⏱️ Auto-Increment Counter

5

Current value: 5

The counter increases by 1 every second using a signal and setInterval.

Deep Dive: Auto-Incrementing with Angular Signals

Auto-incrementing counters are a classic example for learning reactivity. With Angular signals, you can create a value that updates itself on a timer, and the UI will always show the latest value—no manual refresh or change detection needed.

A signal in Angular is a special function that holds a value and notifies the UI whenever it changes. This makes it perfect for dynamic, time-based updates like a ticking counter.

How This Example Works

  • Signal Declaration: The counter value is stored in a signal, e.g. count = signal(0);
  • Auto-Increment Logic: In the component’s TypeScript, setInterval is used to call count.update(c => c + 1) every second. This updates the signal’s value.
  • Reactive UI: The template uses 5 to display the value. Whenever the signal changes, Angular updates the UI automatically.
  • No Subscriptions Needed: Unlike RxJS or manual change detection, signals handle all reactivity for you. The UI stays in sync with the signal’s value.
  • Cleanup: For best practices, always clear your interval in ngOnDestroy to avoid memory leaks.

Why Use Signals for Timers?

  • Simplicity: No need for RxJS, Subjects, or manual subscriptions.
  • Performance: Only the parts of the UI that use the signal are updated.
  • Readability: The code is easy to follow and maintain.
  • Fine-Grained Reactivity: Signals track exactly where they’re used, so updates are efficient.
Angular signals make building dynamic, time-based features like auto-incrementing counters simple, efficient, and fun!