0
# Action Generation
1
2
NgRx action generation schematic that creates type-safe action classes with proper typing and optional API action patterns for success/failure scenarios. Actions are the primary way to express state changes and trigger side effects in NgRx applications.
3
4
## Capabilities
5
6
### Action Schematic
7
8
Generates NgRx action definitions using the createAction function with type safety and payload support.
9
10
```bash
11
# Basic action generation
12
ng generate @ngrx/schematics:action User
13
14
# API action pattern (success/failure actions)
15
ng generate @ngrx/schematics:action User --api
16
17
# Grouped actions in actions folder
18
ng generate @ngrx/schematics:action User --group
19
```
20
21
```typescript { .api }
22
/**
23
* Action schematic configuration interface
24
*/
25
interface ActionSchema {
26
/** Name of the actions (typically entity or feature name) */
27
name: string;
28
/** Prefix for action type strings */
29
prefix?: string;
30
/** Path where action files should be generated */
31
path?: string;
32
/** Angular project to target */
33
project?: string;
34
/** Generate files without creating a folder */
35
flat?: boolean;
36
/** Group action files within 'actions' folder */
37
group?: boolean;
38
/** Generate API success and failure actions */
39
api?: boolean;
40
}
41
```
42
43
### Basic Action Generation
44
45
Creates standard action definitions using NgRx's createAction function.
46
47
```typescript
48
// Generated basic actions
49
import { createAction, props } from '@ngrx/store';
50
51
export const loadUsers = createAction('[User] Load Users');
52
53
export const loadUsersSuccess = createAction(
54
'[User] Load Users Success',
55
props<{ users: User[] }>()
56
);
57
58
export const loadUsersFailure = createAction(
59
'[User] Load Users Failure',
60
props<{ error: string }>()
61
);
62
```
63
64
**Usage Examples:**
65
66
```bash
67
# Generate user actions
68
ng generate @ngrx/schematics:action User --prefix="User Page"
69
70
# Generate product actions with custom path
71
ng generate @ngrx/schematics:action Product --path=src/app/catalog --prefix="Product"
72
```
73
74
### API Action Pattern
75
76
When using `--api` flag, generates complete API action patterns including loading, success, and failure actions.
77
78
```typescript
79
// Generated API actions with --api flag
80
import { createAction, props } from '@ngrx/store';
81
82
// Load actions
83
export const loadUsers = createAction('[User/API] Load Users');
84
85
export const loadUsersSuccess = createAction(
86
'[User/API] Load Users Success',
87
props<{ users: User[] }>()
88
);
89
90
export const loadUsersFailure = createAction(
91
'[User/API] Load Users Failure',
92
props<{ error: any }>()
93
);
94
95
// Create actions
96
export const createUser = createAction(
97
'[User/API] Create User',
98
props<{ user: User }>()
99
);
100
101
export const createUserSuccess = createAction(
102
'[User/API] Create User Success',
103
props<{ user: User }>()
104
);
105
106
export const createUserFailure = createAction(
107
'[User/API] Create User Failure',
108
props<{ error: any }>()
109
);
110
111
// Update actions
112
export const updateUser = createAction(
113
'[User/API] Update User',
114
props<{ user: Update<User> }>()
115
);
116
117
export const updateUserSuccess = createAction(
118
'[User/API] Update User Success',
119
props<{ user: User }>()
120
);
121
122
export const updateUserFailure = createAction(
123
'[User/API] Update User Failure',
124
props<{ error: any }>()
125
);
126
127
// Delete actions
128
export const deleteUser = createAction(
129
'[User/API] Delete User',
130
props<{ id: string }>()
131
);
132
133
export const deleteUserSuccess = createAction(
134
'[User/API] Delete User Success',
135
props<{ id: string }>()
136
);
137
138
export const deleteUserFailure = createAction(
139
'[User/API] Delete User Failure',
140
props<{ error: any }>()
141
);
142
```
143
144
**Usage Examples:**
145
146
```bash
147
# Generate complete API action set
148
ng generate @ngrx/schematics:action Product --api --prefix="Product API"
149
150
# Generate API actions with grouping
151
ng generate @ngrx/schematics:action Order --api --group --prefix="Order"
152
```
153
154
### Action Type Conventions
155
156
The schematic follows NgRx action type conventions with proper categorization:
157
158
```typescript { .api }
159
/**
160
* Action type string format: [Source] Event
161
* Examples:
162
* - [User List] Load Users
163
* - [User API] Load Users Success
164
* - [User Detail] Select User
165
*/
166
interface ActionTypeConvention {
167
source: string; // Component, service, or API source
168
event: string; // What happened
169
outcome?: string; // Success, Failure, etc.
170
}
171
```
172
173
### File Structure Options
174
175
The schematic provides flexible file organization:
176
177
**Flat Structure (--flat):**
178
```
179
src/app/user/
180
├── user.actions.ts
181
├── user.reducer.ts
182
└── user.effects.ts
183
```
184
185
**Grouped Structure (--group):**
186
```
187
src/app/user/
188
├── actions/
189
│ └── user.actions.ts
190
├── reducers/
191
│ └── user.reducer.ts
192
└── effects/
193
└── user.effects.ts
194
```
195
196
**Default Structure:**
197
```
198
src/app/user/
199
└── user/
200
├── user.actions.ts
201
├── user.reducer.ts
202
└── user.effects.ts
203
```
204
205
### Props and Payload Types
206
207
The generated actions include proper TypeScript typing for payloads:
208
209
```typescript
210
// Actions with typed payloads
211
export const selectUser = createAction(
212
'[User] Select User',
213
props<{ userId: string }>()
214
);
215
216
export const updateUserFilter = createAction(
217
'[User] Update Filter',
218
props<{ filter: UserFilter }>()
219
);
220
221
export const clearUsers = createAction('[User] Clear Users');
222
223
// Complex payload types
224
export const searchUsers = createAction(
225
'[User] Search Users',
226
props<{
227
query: string;
228
filters: UserSearchFilters;
229
pagination: PaginationOptions;
230
}>()
231
);
232
```
233
234
### Action Creators
235
236
The schematic generates action creators that can be imported and used throughout the application:
237
238
```typescript { .api }
239
/**
240
* Generated action creators for dispatch and type checking
241
*/
242
interface ActionCreators {
243
[actionName: string]: ActionCreator;
244
}
245
246
// Usage in components and effects
247
import * as UserActions from './user.actions';
248
249
// Dispatch actions
250
this.store.dispatch(UserActions.loadUsers());
251
this.store.dispatch(UserActions.selectUser({ userId: '123' }));
252
```
253
254
### Integration with Effects
255
256
Generated actions are designed to work seamlessly with NgRx Effects:
257
258
```typescript
259
// Example effect using generated actions
260
@Injectable()
261
export class UserEffects {
262
loadUsers$ = createEffect(() =>
263
this.actions$.pipe(
264
ofType(UserActions.loadUsers),
265
switchMap(() =>
266
this.userService.getUsers().pipe(
267
map(users => UserActions.loadUsersSuccess({ users })),
268
catchError(error => of(UserActions.loadUsersFailure({ error })))
269
)
270
)
271
)
272
);
273
}
274
```
275
276
### Barrel Exports
277
278
The schematic updates index.ts files to export all generated actions:
279
280
```typescript
281
// Generated barrel exports
282
export * from './user.actions';
283
export * from './user.reducer';
284
export * from './user.selectors';
285
export * from './user.effects';
286
```
287
288
### Testing Support
289
290
Generated actions are fully testable and include proper type checking:
291
292
```typescript
293
// Example action tests
294
describe('User Actions', () => {
295
it('should create loadUsers action', () => {
296
const action = UserActions.loadUsers();
297
expect(action.type).toBe('[User] Load Users');
298
});
299
300
it('should create loadUsersSuccess action with payload', () => {
301
const users = [{ id: '1', name: 'John' }];
302
const action = UserActions.loadUsersSuccess({ users });
303
expect(action.type).toBe('[User] Load Users Success');
304
expect(action.users).toEqual(users);
305
});
306
});
307
```