Angular Signals: A Complete Guide
Angular Signals are a new reactive primitive introduced in Angular 16+. They provide a simpler way to manage state in your components without the complexity of RxJS for simple use cases.
What are Signals?
A signal is a wrapper around a value that notifies interested consumers when that value changes. Signals can contain any value, from primitives to complex data structures.
Creating Signals
Here's how to create and use signals:
typescript
import { signal, computed } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<div>
<p>Count: {{ count() }}</p>
<p>Double: {{ doubleCount() }}</p>
<button (click)="increment()">Increment</button>
</div>
`
})
export class CounterComponent {
count = signal(0);
doubleCount = computed(() => this.count() * 2);
increment() {
this.count.update(value => value + 1);
}
}Signal Methods
Signals provide three main methods:
- Replace the current valueset(value) - Update based on current valueupdate(fn) - Mutate the value in place (for objects/arrays)mutate(fn)
typescript
const items = signal<string[]>([]);
items.set(['a', 'b', 'c']);
items.update(current => [...current, 'd']);Computed Signals
Computed signals derive their value from other signals:
typescript
const firstName = signal('John');
const lastName = signal('Doe');
const fullName = computed(() => `${firstName()} ${lastName()}`);Effects
Effects run side effects when signals change:
typescript
effect(() => {
console.log('Count changed:', this.count());
});Best Practices
- Use signals for component state
- Use computed for derived values
- Keep effects simple and focused
- Consider RxJS for complex async operations