0 day streak
javascript / intermediate
Snippet

Reactive State with Angular Signals

Signals provide a granular way to track state changes in Angular, allowing the framework to optimize change detection by knowing exactly which parts of the UI need updating.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<button (click)="increment()">Count: {{ count() }}</button>
<p>Double: {{ doubleCount() }}</p>
`
})
export class CounterComponent {
count = signal(0);
doubleCount = computed(() => this.count() * 2);
increment() {
this.count.update(value => value + 1);
}
}
angular
Breakdown
1
count = signal(0);
Initializes a writable signal with a starting value of 0.
2
doubleCount = computed(...);
Creates a derived signal that automatically recalculates when its dependencies change.
3
this.count.update(...);
Updates the signal value based on its current value.