We use cookies to enhance your experience on the site
CodeWorlds

Signal Methods

Creation and Modification

1import { signal } from '@angular/core';
2
3// Creating a signal
4const count = signal(0);               // signal with initial value
5const user = signal<User | null>(null); // signal with type
6
7// Reading the value - call like a function
8console.log(count());  // 0
9
10// set() - sets a new value
11count.set(10);
12
13// update() - updates based on the previous value
14count.update(current => current + 1);  // 11
15
16// asReadonly() - returns a read-only signal
17const readonlyCount = count.asReadonly();

Signals with Objects and Arrays

1interface Samurai {
2  name: string;
3  level: number;
4  skills: string[];
5}
6
7const samurai = signal<Samurai>({
8  name: 'Musashi',
9  level: 1,
10  skills: ['Kendo']
11});
12
13// Updating the entire object
14samurai.update(s => ({
15  ...s,
16  level: s.level + 1
17}));
18
19// Adding to an array
20samurai.update(s => ({
21  ...s,
22  skills: [...s.skills, 'Iaido']
23}));

Computed Signals

1import { computed } from '@angular/core';
2
3const price = signal(100);
4const quantity = signal(2);
5const taxRate = signal(0.23);
6
7// Computed automatically recalculates when dependencies change
8const subtotal = computed(() => price() * quantity());
9const tax = computed(() => subtotal() * taxRate());
10const total = computed(() => subtotal() + tax());
11
12console.log(total());  // 246
13
14price.set(200);
15console.log(total());  // 492 - automatically recalculated!
Go to CodeWorlds