What do you know about Angular Signals? What are the basic APIs and entities?
sobes.tech AI
Answer from AI
Angular Signals are a reactive mechanism for managing state and tracking changes in Angular. They allow creating reactive variables that automatically update related components or computations when their values change.
Basic entities and API of Angular Signals:
-
signal<T>(initialValue: T)— creates a signal with an initial value of type T. -
computed<T>(fn: () => T)— creates a computed signal that automatically recalculates when dependent signals change. -
effect(fn: () => void)— creates a side effect that executes when signals it depends on change. -
Signal methods:
.get()— retrieves the current value of the signal..set(value: T)— sets a new value for the signal.
Example usage:
import { signal, computed, effect } from '@angular/core';
const count = signal(0);
const doubleCount = computed(() => count.get() * 2);
effect(() => {
console.log('Count changed:', count.get());
console.log('Double count:', doubleCount.get());
});
count.set(5); // will automatically trigger effect and update doubleCount
Signals simplify state management, making it more predictable and efficient, reducing the need for complex subscription and unsubscription patterns.