create-huenei-template 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/templates.js +3 -3
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-component/SKILL.md +288 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-component/references/component-patterns.md +358 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-di/SKILL.md +387 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-di/references/di-patterns.md +519 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-directives/SKILL.md +437 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-directives/references/directive-patterns.md +570 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-forms/SKILL.md +434 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-forms/references/form-patterns.md +398 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-http/SKILL.md +366 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-http/references/http-patterns.md +448 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-routing/SKILL.md +395 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-routing/references/routing-patterns.md +472 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-signals/SKILL.md +302 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-signals/references/signal-patterns.md +404 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-ssr/SKILL.md +435 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-ssr/references/ssr-patterns.md +497 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-testing/SKILL.md +660 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-testing/references/testing-patterns.md +707 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-tooling/SKILL.md +352 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/angular-tooling/references/tooling-patterns.md +448 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-accessibility/SKILL.md +780 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-advanced-components/SKILL.md +718 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-advanced-design-systems/SKILL.md +612 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-advanced-layouts/SKILL.md +594 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-animations/SKILL.md +432 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-animations/references/animation-patterns.md +427 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-debugging/SKILL.md +354 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-debugging/references/troubleshooting-guide.md +306 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-framework-integration/SKILL.md +578 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-framework-integration/references/react-patterns.md +353 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-fundamentals-v4/SKILL.md +608 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-fundamentals-v4/references/advanced-theme-patterns.md +215 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-fundamentals-v4/references/custom-utilities-guide.md +281 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-mobile-first/SKILL.md +768 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-performance/SKILL.md +374 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-performance/references/bundle-optimization.md +244 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-plugins/SKILL.md +505 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-responsive-darkmode/SKILL.md +601 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/tailwindcss-responsive-darkmode/references/advanced-responsive-patterns.md +485 -0
- package/dist/templates/frontend/angular-base/.cursor/skills/web-design-guidelines/SKILL.md +39 -0
- package/dist/templates/frontend/angular-base/package.json +0 -1
- package/dist/templates/frontend/angular-base/pnpm-lock.yaml +8183 -0
- package/package.json +1 -1
- package/templates/frontend/angular-base/.cursor/skills/angular-component/SKILL.md +288 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-component/references/component-patterns.md +358 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-di/SKILL.md +387 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-di/references/di-patterns.md +519 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-directives/SKILL.md +437 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-directives/references/directive-patterns.md +570 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-forms/SKILL.md +434 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-forms/references/form-patterns.md +398 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-http/SKILL.md +366 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-http/references/http-patterns.md +448 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-routing/SKILL.md +395 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-routing/references/routing-patterns.md +472 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-signals/SKILL.md +302 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-signals/references/signal-patterns.md +404 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-ssr/SKILL.md +435 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-ssr/references/ssr-patterns.md +497 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-testing/SKILL.md +660 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-testing/references/testing-patterns.md +707 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-tooling/SKILL.md +352 -0
- package/templates/frontend/angular-base/.cursor/skills/angular-tooling/references/tooling-patterns.md +448 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-accessibility/SKILL.md +780 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-advanced-components/SKILL.md +718 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-advanced-design-systems/SKILL.md +612 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-advanced-layouts/SKILL.md +594 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-animations/SKILL.md +432 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-animations/references/animation-patterns.md +427 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-debugging/SKILL.md +354 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-debugging/references/troubleshooting-guide.md +306 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-framework-integration/SKILL.md +578 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-framework-integration/references/react-patterns.md +353 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-fundamentals-v4/SKILL.md +608 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-fundamentals-v4/references/advanced-theme-patterns.md +215 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-fundamentals-v4/references/custom-utilities-guide.md +281 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-mobile-first/SKILL.md +768 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-performance/SKILL.md +374 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-performance/references/bundle-optimization.md +244 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-plugins/SKILL.md +505 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-responsive-darkmode/SKILL.md +601 -0
- package/templates/frontend/angular-base/.cursor/skills/tailwindcss-responsive-darkmode/references/advanced-responsive-patterns.md +485 -0
- package/templates/frontend/angular-base/.cursor/skills/web-design-guidelines/SKILL.md +39 -0
- package/templates/frontend/angular-base/package.json +0 -1
- package/templates/frontend/angular-base/pnpm-lock.yaml +8183 -0
- package/templates/frontend/angular-base/package-lock.json +0 -13321
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: angular-signals
|
|
3
|
+
description: Implement signal-based reactive state management in Angular v20+. Use for creating reactive state with signal(), derived state with computed(), dependent state with linkedSignal(), and side effects with effect(). Triggers on state management questions, converting from BehaviorSubject/Observable patterns to signals, or implementing reactive data flows.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Angular Signals
|
|
7
|
+
|
|
8
|
+
Signals are Angular's reactive primitive for state management. They provide synchronous, fine-grained reactivity.
|
|
9
|
+
|
|
10
|
+
## Core Signal APIs
|
|
11
|
+
|
|
12
|
+
### signal() - Writable State
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
import { signal } from '@angular/core';
|
|
16
|
+
|
|
17
|
+
// Create writable signal
|
|
18
|
+
const count = signal(0);
|
|
19
|
+
|
|
20
|
+
// Read value
|
|
21
|
+
console.log(count()); // 0
|
|
22
|
+
|
|
23
|
+
// Set new value
|
|
24
|
+
count.set(5);
|
|
25
|
+
|
|
26
|
+
// Update based on current value
|
|
27
|
+
count.update(c => c + 1);
|
|
28
|
+
|
|
29
|
+
// With explicit type
|
|
30
|
+
const user = signal<User | null>(null);
|
|
31
|
+
user.set({ id: 1, name: 'Alice' });
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### computed() - Derived State
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { signal, computed } from '@angular/core';
|
|
38
|
+
|
|
39
|
+
const firstName = signal('John');
|
|
40
|
+
const lastName = signal('Doe');
|
|
41
|
+
|
|
42
|
+
// Derived signal - automatically updates when dependencies change
|
|
43
|
+
const fullName = computed(() => `${firstName()} ${lastName()}`);
|
|
44
|
+
|
|
45
|
+
console.log(fullName()); // "John Doe"
|
|
46
|
+
firstName.set('Jane');
|
|
47
|
+
console.log(fullName()); // "Jane Doe"
|
|
48
|
+
|
|
49
|
+
// Computed with complex logic
|
|
50
|
+
const items = signal<Item[]>([]);
|
|
51
|
+
const filter = signal('');
|
|
52
|
+
|
|
53
|
+
const filteredItems = computed(() => {
|
|
54
|
+
const query = filter().toLowerCase();
|
|
55
|
+
return items().filter(item =>
|
|
56
|
+
item.name.toLowerCase().includes(query)
|
|
57
|
+
);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const totalPrice = computed(() =>
|
|
61
|
+
filteredItems().reduce((sum, item) => sum + item.price, 0)
|
|
62
|
+
);
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### linkedSignal() - Dependent State with Reset
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
import { signal, linkedSignal } from '@angular/core';
|
|
69
|
+
|
|
70
|
+
const options = signal(['A', 'B', 'C']);
|
|
71
|
+
|
|
72
|
+
// Resets to first option when options change
|
|
73
|
+
const selected = linkedSignal(() => options()[0]);
|
|
74
|
+
|
|
75
|
+
console.log(selected()); // "A"
|
|
76
|
+
selected.set('B'); // User selects B
|
|
77
|
+
console.log(selected()); // "B"
|
|
78
|
+
options.set(['X', 'Y']); // Options change
|
|
79
|
+
console.log(selected()); // "X" - auto-reset to first
|
|
80
|
+
|
|
81
|
+
// With previous value access
|
|
82
|
+
const items = signal<Item[]>([]);
|
|
83
|
+
|
|
84
|
+
const selectedItem = linkedSignal<Item[], Item | null>({
|
|
85
|
+
source: () => items(),
|
|
86
|
+
computation: (newItems, previous) => {
|
|
87
|
+
// Try to preserve selection if item still exists
|
|
88
|
+
const prevItem = previous?.value;
|
|
89
|
+
if (prevItem && newItems.some(i => i.id === prevItem.id)) {
|
|
90
|
+
return prevItem;
|
|
91
|
+
}
|
|
92
|
+
return newItems[0] ?? null;
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### effect() - Side Effects
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { signal, effect, inject, DestroyRef } from '@angular/core';
|
|
101
|
+
|
|
102
|
+
@Component({...})
|
|
103
|
+
export class Search {
|
|
104
|
+
query = signal('');
|
|
105
|
+
|
|
106
|
+
constructor() {
|
|
107
|
+
// Effect runs when query changes
|
|
108
|
+
effect(() => {
|
|
109
|
+
console.log('Search query:', this.query());
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// Effect with cleanup
|
|
113
|
+
effect((onCleanup) => {
|
|
114
|
+
const timer = setInterval(() => {
|
|
115
|
+
console.log('Current query:', this.query());
|
|
116
|
+
}, 1000);
|
|
117
|
+
|
|
118
|
+
onCleanup(() => clearInterval(timer));
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
**Effect rules:**
|
|
125
|
+
- Run in injection context (constructor or with `runInInjectionContext`)
|
|
126
|
+
- Automatically cleaned up when component destroys
|
|
127
|
+
|
|
128
|
+
## Component State Pattern
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
@Component({
|
|
132
|
+
selector: 'app-todo-list',
|
|
133
|
+
template: `
|
|
134
|
+
<input [value]="newTodo()" (input)="newTodo.set($any($event.target).value)" />
|
|
135
|
+
<button (click)="addTodo()" [disabled]="!canAdd()">Add</button>
|
|
136
|
+
|
|
137
|
+
<ul>
|
|
138
|
+
@for (todo of filteredTodos(); track todo.id) {
|
|
139
|
+
<li [class.done]="todo.done">
|
|
140
|
+
{{ todo.text }}
|
|
141
|
+
<button (click)="toggleTodo(todo.id)">Toggle</button>
|
|
142
|
+
</li>
|
|
143
|
+
}
|
|
144
|
+
</ul>
|
|
145
|
+
|
|
146
|
+
<p>{{ remaining() }} remaining</p>
|
|
147
|
+
`,
|
|
148
|
+
})
|
|
149
|
+
export class TodoList {
|
|
150
|
+
// State
|
|
151
|
+
todos = signal<Todo[]>([]);
|
|
152
|
+
newTodo = signal('');
|
|
153
|
+
filter = signal<'all' | 'active' | 'done'>('all');
|
|
154
|
+
|
|
155
|
+
// Derived state
|
|
156
|
+
canAdd = computed(() => this.newTodo().trim().length > 0);
|
|
157
|
+
|
|
158
|
+
filteredTodos = computed(() => {
|
|
159
|
+
const todos = this.todos();
|
|
160
|
+
switch (this.filter()) {
|
|
161
|
+
case 'active': return todos.filter(t => !t.done);
|
|
162
|
+
case 'done': return todos.filter(t => t.done);
|
|
163
|
+
default: return todos;
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
remaining = computed(() =>
|
|
168
|
+
this.todos().filter(t => !t.done).length
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
// Actions
|
|
172
|
+
addTodo() {
|
|
173
|
+
const text = this.newTodo().trim();
|
|
174
|
+
if (text) {
|
|
175
|
+
this.todos.update(todos => [
|
|
176
|
+
...todos,
|
|
177
|
+
{ id: crypto.randomUUID(), text, done: false }
|
|
178
|
+
]);
|
|
179
|
+
this.newTodo.set('');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
toggleTodo(id: string) {
|
|
184
|
+
this.todos.update(todos =>
|
|
185
|
+
todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## RxJS Interop
|
|
192
|
+
|
|
193
|
+
### toSignal() - Observable to Signal
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
import { toSignal } from '@angular/core/rxjs-interop';
|
|
197
|
+
import { interval } from 'rxjs';
|
|
198
|
+
|
|
199
|
+
@Component({...})
|
|
200
|
+
export class Timer {
|
|
201
|
+
private http = inject(HttpClient);
|
|
202
|
+
|
|
203
|
+
// From observable - requires initial value or allowUndefined
|
|
204
|
+
counter = toSignal(interval(1000), { initialValue: 0 });
|
|
205
|
+
|
|
206
|
+
// From HTTP - undefined until loaded
|
|
207
|
+
users = toSignal(this.http.get<User[]>('/api/users'));
|
|
208
|
+
|
|
209
|
+
// With requireSync for synchronous observables (BehaviorSubject)
|
|
210
|
+
private user$ = new BehaviorSubject<User | null>(null);
|
|
211
|
+
currentUser = toSignal(this.user$, { requireSync: true });
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### toObservable() - Signal to Observable
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { toObservable } from '@angular/core/rxjs-interop';
|
|
219
|
+
import { switchMap, debounceTime } from 'rxjs';
|
|
220
|
+
|
|
221
|
+
@Component({...})
|
|
222
|
+
export class Search {
|
|
223
|
+
query = signal('');
|
|
224
|
+
|
|
225
|
+
private http = inject(HttpClient);
|
|
226
|
+
|
|
227
|
+
// Convert signal to observable for RxJS operators
|
|
228
|
+
results = toSignal(
|
|
229
|
+
toObservable(this.query).pipe(
|
|
230
|
+
debounceTime(300),
|
|
231
|
+
switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`))
|
|
232
|
+
),
|
|
233
|
+
{ initialValue: [] }
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Signal Equality
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
// Custom equality function
|
|
242
|
+
const user = signal<User>(
|
|
243
|
+
{ id: 1, name: 'Alice' },
|
|
244
|
+
{ equal: (a, b) => a.id === b.id }
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
// Only triggers updates when ID changes
|
|
248
|
+
user.set({ id: 1, name: 'Alice Updated' }); // No update
|
|
249
|
+
user.set({ id: 2, name: 'Bob' }); // Triggers update
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Untracked Reads
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
import { untracked } from '@angular/core';
|
|
256
|
+
|
|
257
|
+
const a = signal(1);
|
|
258
|
+
const b = signal(2);
|
|
259
|
+
|
|
260
|
+
// Only depends on 'a', not 'b'
|
|
261
|
+
const result = computed(() => {
|
|
262
|
+
const aVal = a();
|
|
263
|
+
const bVal = untracked(() => b());
|
|
264
|
+
return aVal + bVal;
|
|
265
|
+
});
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## Service State Pattern
|
|
269
|
+
|
|
270
|
+
```typescript
|
|
271
|
+
@Injectable({ providedIn: 'root' })
|
|
272
|
+
export class Auth {
|
|
273
|
+
// Private writable state
|
|
274
|
+
private _user = signal<User | null>(null);
|
|
275
|
+
private _loading = signal(false);
|
|
276
|
+
|
|
277
|
+
// Public read-only signals
|
|
278
|
+
readonly user = this._user.asReadonly();
|
|
279
|
+
readonly loading = this._loading.asReadonly();
|
|
280
|
+
readonly isAuthenticated = computed(() => this._user() !== null);
|
|
281
|
+
|
|
282
|
+
private http = inject(HttpClient);
|
|
283
|
+
|
|
284
|
+
async login(credentials: Credentials): Promise<void> {
|
|
285
|
+
this._loading.set(true);
|
|
286
|
+
try {
|
|
287
|
+
const user = await firstValueFrom(
|
|
288
|
+
this.http.post<User>('/api/login', credentials)
|
|
289
|
+
);
|
|
290
|
+
this._user.set(user);
|
|
291
|
+
} finally {
|
|
292
|
+
this._loading.set(false);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
logout(): void {
|
|
297
|
+
this._user.set(null);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
For advanced patterns including resource(), see [references/signal-patterns.md](references/signal-patterns.md).
|
package/templates/frontend/angular-base/.cursor/skills/angular-signals/references/signal-patterns.md
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
# Angular Signal Patterns
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
- [Resource API](#resource-api)
|
|
5
|
+
- [Signal Store Pattern](#signal-store-pattern)
|
|
6
|
+
- [Form State with Signals](#form-state-with-signals)
|
|
7
|
+
- [Async Operations](#async-operations)
|
|
8
|
+
- [Testing Signals](#testing-signals)
|
|
9
|
+
|
|
10
|
+
## Resource API
|
|
11
|
+
|
|
12
|
+
The `resource()` API handles async data fetching with signals:
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
import { resource, signal, computed } from '@angular/core';
|
|
16
|
+
|
|
17
|
+
@Component({...})
|
|
18
|
+
export class UserProfile {
|
|
19
|
+
userId = signal<string>('');
|
|
20
|
+
|
|
21
|
+
// Resource fetches data when params change
|
|
22
|
+
userResource = resource({
|
|
23
|
+
params: () => ({ id: this.userId() }),
|
|
24
|
+
loader: async ({ params, abortSignal }) => {
|
|
25
|
+
const response = await fetch(`/api/users/${params.id}`, {
|
|
26
|
+
signal: abortSignal,
|
|
27
|
+
});
|
|
28
|
+
return response.json() as Promise<User>;
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Access resource state
|
|
33
|
+
user = computed(() => this.userResource.value());
|
|
34
|
+
isLoading = computed(() => this.userResource.isLoading());
|
|
35
|
+
error = computed(() => this.userResource.error());
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Resource Status
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
const userResource = resource({...});
|
|
43
|
+
|
|
44
|
+
// Status signals
|
|
45
|
+
userResource.value(); // Current value or undefined
|
|
46
|
+
userResource.hasValue(); // Boolean - has resolved value
|
|
47
|
+
userResource.error(); // Error or undefined
|
|
48
|
+
userResource.isLoading(); // Boolean - currently loading
|
|
49
|
+
userResource.status(); // 'idle' | 'loading' | 'reloading' | 'resolved' | 'error' | 'local'
|
|
50
|
+
|
|
51
|
+
// Manual reload
|
|
52
|
+
userResource.reload();
|
|
53
|
+
|
|
54
|
+
// Local updates
|
|
55
|
+
userResource.set(newValue);
|
|
56
|
+
userResource.update(current => ({ ...current, name: 'Updated' }));
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Resource with Default Value
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
const todosResource = resource({
|
|
63
|
+
defaultValue: [] as Todo[],
|
|
64
|
+
params: () => ({ filter: this.filter() }),
|
|
65
|
+
loader: async ({ params }) => {
|
|
66
|
+
const response = await fetch(`/api/todos?filter=${params.filter}`);
|
|
67
|
+
return response.json();
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// value() returns Todo[] (never undefined due to defaultValue)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Conditional Loading
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
const userId = signal<string | null>(null);
|
|
78
|
+
|
|
79
|
+
const userResource = resource({
|
|
80
|
+
params: () => {
|
|
81
|
+
const id = userId();
|
|
82
|
+
// Return undefined to skip loading
|
|
83
|
+
return id ? { id } : undefined;
|
|
84
|
+
},
|
|
85
|
+
loader: async ({ params }) => {
|
|
86
|
+
return fetch(`/api/users/${params.id}`).then(r => r.json());
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
// Status is 'idle' when params returns undefined
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Signal Store Pattern
|
|
93
|
+
|
|
94
|
+
For complex state, create a dedicated store:
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
interface ProductState {
|
|
98
|
+
products: Product[];
|
|
99
|
+
selectedId: string | null;
|
|
100
|
+
filter: string;
|
|
101
|
+
loading: boolean;
|
|
102
|
+
error: string | null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
@Injectable({ providedIn: 'root' })
|
|
106
|
+
export class ProductSt {
|
|
107
|
+
// Private state
|
|
108
|
+
private state = signal<ProductState>({
|
|
109
|
+
products: [],
|
|
110
|
+
selectedId: null,
|
|
111
|
+
filter: '',
|
|
112
|
+
loading: false,
|
|
113
|
+
error: null,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// Selectors (computed signals)
|
|
117
|
+
readonly products = computed(() => this.state().products);
|
|
118
|
+
readonly selectedId = computed(() => this.state().selectedId);
|
|
119
|
+
readonly filter = computed(() => this.state().filter);
|
|
120
|
+
readonly loading = computed(() => this.state().loading);
|
|
121
|
+
readonly error = computed(() => this.state().error);
|
|
122
|
+
|
|
123
|
+
readonly filteredProducts = computed(() => {
|
|
124
|
+
const { products, filter } = this.state();
|
|
125
|
+
if (!filter) return products;
|
|
126
|
+
return products.filter(p =>
|
|
127
|
+
p.name.toLowerCase().includes(filter.toLowerCase())
|
|
128
|
+
);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
readonly selectedProduct = computed(() => {
|
|
132
|
+
const { products, selectedId } = this.state();
|
|
133
|
+
return products.find(p => p.id === selectedId) ?? null;
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
private http = inject(HttpClient);
|
|
137
|
+
|
|
138
|
+
// Actions
|
|
139
|
+
setFilter(filter: string): void {
|
|
140
|
+
this.state.update(s => ({ ...s, filter }));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
selectProduct(id: string | null): void {
|
|
144
|
+
this.state.update(s => ({ ...s, selectedId: id }));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async loadProducts(): Promise<void> {
|
|
148
|
+
this.state.update(s => ({ ...s, loading: true, error: null }));
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
const products = await firstValueFrom(
|
|
152
|
+
this.http.get<Product[]>('/api/products')
|
|
153
|
+
);
|
|
154
|
+
this.state.update(s => ({ ...s, products, loading: false }));
|
|
155
|
+
} catch (err) {
|
|
156
|
+
this.state.update(s => ({
|
|
157
|
+
...s,
|
|
158
|
+
loading: false,
|
|
159
|
+
error: 'Failed to load products'
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async addProduct(product: Omit<Product, 'id'>): Promise<void> {
|
|
165
|
+
const newProduct = await firstValueFrom(
|
|
166
|
+
this.http.post<Product>('/api/products', product)
|
|
167
|
+
);
|
|
168
|
+
this.state.update(s => ({
|
|
169
|
+
...s,
|
|
170
|
+
products: [...s.products, newProduct],
|
|
171
|
+
}));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Form State with Signals
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
interface FormState<T> {
|
|
180
|
+
value: T;
|
|
181
|
+
touched: boolean;
|
|
182
|
+
dirty: boolean;
|
|
183
|
+
valid: boolean;
|
|
184
|
+
errors: string[];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function createFormField<T>(
|
|
188
|
+
initialValue: T,
|
|
189
|
+
validators: ((value: T) => string | null)[] = []
|
|
190
|
+
) {
|
|
191
|
+
const value = signal(initialValue);
|
|
192
|
+
const touched = signal(false);
|
|
193
|
+
const dirty = signal(false);
|
|
194
|
+
|
|
195
|
+
const errors = computed(() => {
|
|
196
|
+
return validators
|
|
197
|
+
.map(v => v(value()))
|
|
198
|
+
.filter((e): e is string => e !== null);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
const valid = computed(() => errors().length === 0);
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
value,
|
|
205
|
+
touched: touched.asReadonly(),
|
|
206
|
+
dirty: dirty.asReadonly(),
|
|
207
|
+
errors,
|
|
208
|
+
valid,
|
|
209
|
+
|
|
210
|
+
setValue(newValue: T) {
|
|
211
|
+
value.set(newValue);
|
|
212
|
+
dirty.set(true);
|
|
213
|
+
},
|
|
214
|
+
|
|
215
|
+
markTouched() {
|
|
216
|
+
touched.set(true);
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
reset() {
|
|
220
|
+
value.set(initialValue);
|
|
221
|
+
touched.set(false);
|
|
222
|
+
dirty.set(false);
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Usage
|
|
228
|
+
@Component({...})
|
|
229
|
+
export class Signup {
|
|
230
|
+
email = createFormField('', [
|
|
231
|
+
v => !v ? 'Email is required' : null,
|
|
232
|
+
v => !v.includes('@') ? 'Invalid email' : null,
|
|
233
|
+
]);
|
|
234
|
+
|
|
235
|
+
password = createFormField('', [
|
|
236
|
+
v => !v ? 'Password is required' : null,
|
|
237
|
+
v => v.length < 8 ? 'Password must be at least 8 characters' : null,
|
|
238
|
+
]);
|
|
239
|
+
|
|
240
|
+
formValid = computed(() =>
|
|
241
|
+
this.email.valid() && this.password.valid()
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## Async Operations
|
|
247
|
+
|
|
248
|
+
### Debounced Search
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
@Component({...})
|
|
252
|
+
export class Search {
|
|
253
|
+
query = signal('');
|
|
254
|
+
|
|
255
|
+
private http = inject(HttpClient);
|
|
256
|
+
|
|
257
|
+
// Debounced search using toObservable
|
|
258
|
+
results = toSignal(
|
|
259
|
+
toObservable(this.query).pipe(
|
|
260
|
+
debounceTime(300),
|
|
261
|
+
distinctUntilChanged(),
|
|
262
|
+
filter(q => q.length >= 2),
|
|
263
|
+
switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`)),
|
|
264
|
+
catchError(() => of([]))
|
|
265
|
+
),
|
|
266
|
+
{ initialValue: [] }
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
// Loading state
|
|
270
|
+
private searching = signal(false);
|
|
271
|
+
readonly isSearching = this.searching.asReadonly();
|
|
272
|
+
|
|
273
|
+
constructor() {
|
|
274
|
+
// Track loading state
|
|
275
|
+
effect(() => {
|
|
276
|
+
const q = this.query();
|
|
277
|
+
if (q.length >= 2) {
|
|
278
|
+
this.searching.set(true);
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
effect(() => {
|
|
283
|
+
this.results(); // Subscribe to results
|
|
284
|
+
this.searching.set(false);
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
### Optimistic Updates
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
@Injectable({ providedIn: 'root' })
|
|
294
|
+
export class Todo {
|
|
295
|
+
private todos = signal<Todo[]>([]);
|
|
296
|
+
readonly items = this.todos.asReadonly();
|
|
297
|
+
|
|
298
|
+
private http = inject(HttpClient);
|
|
299
|
+
|
|
300
|
+
async toggleTodo(id: string): Promise<void> {
|
|
301
|
+
// Optimistic update
|
|
302
|
+
const previousTodos = this.todos();
|
|
303
|
+
this.todos.update(todos =>
|
|
304
|
+
todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
try {
|
|
308
|
+
await firstValueFrom(
|
|
309
|
+
this.http.patch(`/api/todos/${id}/toggle`, {})
|
|
310
|
+
);
|
|
311
|
+
} catch {
|
|
312
|
+
// Rollback on error
|
|
313
|
+
this.todos.set(previousTodos);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## Testing Signals
|
|
320
|
+
|
|
321
|
+
```typescript
|
|
322
|
+
describe('Counter', () => {
|
|
323
|
+
it('should increment count', () => {
|
|
324
|
+
const component = new Counter();
|
|
325
|
+
|
|
326
|
+
expect(component.count()).toBe(0);
|
|
327
|
+
|
|
328
|
+
component.increment();
|
|
329
|
+
expect(component.count()).toBe(1);
|
|
330
|
+
|
|
331
|
+
component.increment();
|
|
332
|
+
expect(component.count()).toBe(2);
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it('should compute doubled value', () => {
|
|
336
|
+
const component = new Counter();
|
|
337
|
+
|
|
338
|
+
expect(component.doubled()).toBe(0);
|
|
339
|
+
|
|
340
|
+
component.count.set(5);
|
|
341
|
+
expect(component.doubled()).toBe(10);
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
describe('ProductSt', () => {
|
|
346
|
+
let store: ProductSt;
|
|
347
|
+
let httpMock: HttpTestingController;
|
|
348
|
+
|
|
349
|
+
beforeEach(() => {
|
|
350
|
+
TestBed.configureTestingModule({
|
|
351
|
+
providers: [
|
|
352
|
+
ProductSt,
|
|
353
|
+
provideHttpClient(),
|
|
354
|
+
provideHttpClientTesting(),
|
|
355
|
+
],
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
store = TestBed.inject(ProductSt);
|
|
359
|
+
httpMock = TestBed.inject(HttpTestingController);
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('should filter products', () => {
|
|
363
|
+
// Set initial state
|
|
364
|
+
store['state'].set({
|
|
365
|
+
products: [
|
|
366
|
+
{ id: '1', name: 'Apple' },
|
|
367
|
+
{ id: '2', name: 'Banana' },
|
|
368
|
+
],
|
|
369
|
+
selectedId: null,
|
|
370
|
+
filter: '',
|
|
371
|
+
loading: false,
|
|
372
|
+
error: null,
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
expect(store.filteredProducts().length).toBe(2);
|
|
376
|
+
|
|
377
|
+
store.setFilter('app');
|
|
378
|
+
expect(store.filteredProducts().length).toBe(1);
|
|
379
|
+
expect(store.filteredProducts()[0].name).toBe('Apple');
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
## Signal Debugging
|
|
385
|
+
|
|
386
|
+
```typescript
|
|
387
|
+
// Debug effect to log signal changes
|
|
388
|
+
effect(() => {
|
|
389
|
+
console.log('State changed:', {
|
|
390
|
+
count: this.count(),
|
|
391
|
+
items: this.items(),
|
|
392
|
+
filter: this.filter(),
|
|
393
|
+
});
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
// Conditional debugging
|
|
397
|
+
const DEBUG = signal(false);
|
|
398
|
+
|
|
399
|
+
effect(() => {
|
|
400
|
+
if (untracked(() => DEBUG())) {
|
|
401
|
+
console.log('Debug:', this.state());
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
```
|