Gathering detailed insights and metrics for @angular-architects/ngrx-toolkit
Gathering detailed insights and metrics for @angular-architects/ngrx-toolkit
Gathering detailed insights and metrics for @angular-architects/ngrx-toolkit
Gathering detailed insights and metrics for @angular-architects/ngrx-toolkit
Various Extensions for the NgRx Signal Store
npm install @angular-architects/ngrx-toolkit
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
177 Stars
91 Commits
23 Forks
8 Watching
5 Branches
14 Contributors
Updated on 28 Nov 2024
TypeScript (88.36%)
HTML (9.87%)
JavaScript (0.93%)
CSS (0.44%)
Shell (0.36%)
SCSS (0.04%)
Cumulative downloads
Total Downloads
Last day
-7.3%
2,616
Compared to previous day
Last week
21.2%
14,341
Compared to previous week
Last month
44.3%
50,505
Compared to previous month
Last year
0%
243,278
Compared to previous year
1
2
NgRx Toolkit is an extension to the NgRx Signals Store. It is still in beta but already offers features, like:
To install it, run
1npm i @angular-architects/ngrx-toolkit
withDevtools()
Redux Devtools is a powerful browser extension tool, that allows you to inspect every change in your stores. Originally, it was designed for Redux, but it can also be used with the SignalStore. You can download it for Chrome here.
To use the Devtools, you need to add the withDevtools()
extension to your SignalStore:
1export const FlightStore = signalStore( 2 { providedIn: 'root' }, 3 withDevtools('flights'), // <-- add this 4 withState({ flights: [] as Flight[] }) 5 // ... 6);
After that, open your app and navigate to the component that uses the store. Open the Devtools and you will see the flights
store in the Devtools under the name "NgRx Signal Store"
You can find a working example in the demo app.
Important: The extensions don't activate them during app initialization (as it is with @ngrx/store
). You need to open the Devtools and select the "NgRx Signal Store" tab to activate it.
The Signal Store does not use the Redux pattern, so there are no action names involved by default. Instead, every action is referred to as a "Store Update". However, if you want to customize the action name for better clarity, you can use the updateState
method instead of patchState
:
1patchState(this.store, { loading: false }); 2 3// updateState is a wrapper around patchState and has an action name as second parameter 4updateState(this.store, 'update loading', { loading: false });
withDevtools()
is by default enabled in production mode, if you want to tree-shake it from the application bundle you need to abstract it in your environment file.
It is required to add the withDevtools
function to the environment files.
environments/environment.ts:
1import { withDevtools } from '@angular-architects/ngrx-toolkit'; 2 3export const environment = { 4 storeWithDevTools: withDevtools 5}
environments/environment.prod.ts
1import { withDevtoolsStub } from '@angular-architects/ngrx-toolkit'; 2 3export const environment = { 4 storeWithDevTools: withDevToolsStub 5}
Then you can create utility function which can be used across the application e.g.:
shared/store.features.ts (or any other file)
1import { environment } from 'src/environments/environment'; 2 3export const withTreeShakableDevTools = environment.storeWithDevTools;
And use it in your store definitions:
1export const SomeStore = signalStore( 2 withState({strings: [] as string[] }), 3 withTreeShakableDevTools('featureName') 4);
Also make sure you have defined file replacements in angular.json prod configuration:
1"fileReplacements": [ 2 { 3 "replace": "src/environments/environment.ts", 4 "with": "src/environments/environment.prod.ts" 5 } 6]
withRedux()
withRedux()
bring back the Redux pattern into the Signal Store.
It can be combined with any other extension of the Signal Store.
Example:
1export const FlightStore = signalStore( 2 { providedIn: 'root' }, 3 withState({ flights: [] as Flight[] }), 4 withRedux({ 5 actions: { 6 public: { 7 load: payload<{ from: string; to: string }>(), 8 }, 9 private: { 10 loaded: payload<{ flights: Flight[] }>(), 11 }, 12 }, 13 reducer(actions, on) { 14 on(actions.loaded, ({ flights }, state) => { 15 patchState(state, 'flights loaded', { flights }); 16 }); 17 }, 18 effects(actions, create) { 19 const httpClient = inject(HttpClient); 20 return { 21 load$: create(actions.load).pipe( 22 switchMap(({ from, to }) => 23 httpClient.get<Flight[]>('https://demo.angulararchitects.io/api/flight', { 24 params: new HttpParams().set('from', from).set('to', to), 25 }) 26 ), 27 tap((flights) => actions.loaded({ flights })) 28 ), 29 }; 30 }, 31 }) 32);
withDataService()
withDataService()
allows to connect a Data Service to the store:
This gives you a store for a CRUD use case:
1export const SimpleFlightBookingStore = signalStore( 2 { providedIn: 'root' }, 3 withCallState(), 4 withEntities<Flight>(), 5 withDataService({ 6 dataServiceType: FlightService, 7 filter: { from: 'Paris', to: 'New York' }, 8 }), 9 withUndoRedo() 10);
The features withCallState
and withUndoRedo
are optional, but when present, they enrich each other.
Refer to the Undo-Redo section for more information.
The Data Service needs to implement the DataService
interface:
1@Injectable({ 2 providedIn: 'root' 3}) 4export class FlightService implements DataService<Flight, FlightFilter> { 5 loadById(id: EntityId): Promise<Flight> { ... } 6 load(filter: FlightFilter): Promise<Flight[]> { ... } 7 8 create(entity: Flight): Promise<Flight> { ... } 9 update(entity: Flight): Promise<Flight> { ... } 10 updateAll(entity: Flight[]): Promise<Flight[]> { ... } 11 delete(entity: Flight): Promise<void> { ... } 12 [...] 13}
Once the store is defined, it gives its consumers numerous signals and methods they just need to delegate to:
1@Component(...) 2export class FlightSearchSimpleComponent { 3 private store = inject(SimpleFlightBookingStore); 4 5 from = this.store.filter.from; 6 to = this.store.filter.to; 7 flights = this.store.entities; 8 selected = this.store.selectedEntities; 9 selectedIds = this.store.selectedIds; 10 11 loading = this.store.loading; 12 13 canUndo = this.store.canUndo; 14 canRedo = this.store.canRedo; 15 16 async search() { 17 this.store.load(); 18 } 19 20 undo(): void { 21 this.store.undo(); 22 } 23 24 redo(): void { 25 this.store.redo(); 26 } 27 28 updateCriteria(from: string, to: string): void { 29 this.store.updateFilter({ from, to }); 30 } 31 32 updateBasket(id: number, selected: boolean): void { 33 this.store.updateSelected(id, selected); 34 } 35 36}
To avoid naming conflicts, the properties set up by withDataService
and the connected features can be configured in a typesafe way:
1export const FlightBookingStore = signalStore( 2 { providedIn: 'root' }, 3 withCallState({ 4 collection: 'flight', 5 }), 6 withEntities({ 7 entity: type<Flight>(), 8 collection: 'flight', 9 }), 10 withDataService({ 11 dataServiceType: FlightService, 12 filter: { from: 'Graz', to: 'Hamburg' }, 13 collection: 'flight', 14 }), 15 withUndoRedo({ 16 collections: ['flight'], 17 }) 18);
This setup makes them use flight
as part of the used property names. As these implementations respect the Type Script type system, the compiler will make sure these properties are used in a typesafe way:
1@Component(...) 2export class FlightSearchDynamicComponent { 3 private store = inject(FlightBookingStore); 4 5 from = this.store.flightFilter.from; 6 to = this.store.flightFilter.to; 7 flights = this.store.flightEntities; 8 selected = this.store.selectedFlightEntities; 9 selectedIds = this.store.selectedFlightIds; 10 11 loading = this.store.flightLoading; 12 13 canUndo = this.store.canUndo; 14 canRedo = this.store.canRedo; 15 16 async search() { 17 this.store.loadFlightEntities(); 18 } 19 20 undo(): void { 21 this.store.undo(); 22 } 23 24 redo(): void { 25 this.store.redo(); 26 } 27 28 updateCriteria(from: string, to: string): void { 29 this.store.updateFlightFilter({ from, to }); 30 } 31 32 updateBasket(id: number, selected: boolean): void { 33 this.store.updateSelectedFlightEntities(id, selected); 34 } 35 36}
withStorageSync()
withStorageSync
adds automatic or manual synchronization with Web Storage (localstorage
/sessionstorage
).
[!WARNING] As Web Storage only works in browser environments it will fallback to a stub implementation on server environments.
Example:
1const SyncStore = signalStore(
2 withStorageSync<User>({
3 key: 'synced', // key used when writing to/reading from storage
4 autoSync: false, // read from storage on init and write on state changes - `true` by default
5 select: (state: User) => Partial<User>, // projection to keep specific slices in sync
6 parse: (stateString: string) => State, // custom parsing from storage - `JSON.parse` by default
7 stringify: (state: User) => string, // custom stringification - `JSON.stringify` by default
8 storage: () => sessionstorage, // factory to select storage to sync with
9 })
10);
1@Component(...) 2public class SyncedStoreComponent { 3 private syncStore = inject(SyncStore); 4 5 updateFromStorage(): void { 6 this.syncStore.readFromStorage(); // reads the stored item from storage and patches the state 7 } 8 9 updateStorage(): void { 10 this.syncStore.writeToStorage(); // writes the current state to storage 11 } 12 13 clearStorage(): void { 14 this.syncStore.clearStorage(); // clears the stored item in storage 15 } 16}
withUndoRedo()
withUndoRedo
adds undo and redo functionality to the store.
Example:
1const SyncStore = signalStore(
2 withUndoRedo({
3 maxStackSize: 100, // limit of undo/redo steps - `100` by default
4 collections: ['flight'], // entity collections to keep track of - unnamed collection is tracked by default
5 keys: ['test'], // non-entity based keys to track - `[]` by default
6 skip: 0, // number of initial state changes to skip - `0` by default
7 })
8);
1@Component(...) 2public class UndoRedoComponent { 3 private syncStore = inject(SyncStore); 4 5 canUndo = this.store.canUndo; // use in template or in ts 6 canRedo = this.store.canRedo; // use in template or in ts 7 8 undo(): void { 9 if (!this.canUndo()) return; 10 this.store.undo(); 11 } 12 13 redo(): void { 14 if (!this.canRedo()) return; 15 this.store.redo(); 16 } 17}
createReduxState()
The Redux Connector turns any signalStore()
into a Global State Management Slice following the Redux pattern. It is available as secondary entry point, i.e. import { createReduxState } from '@angular-architects/ngrx-toolkit/redux-connector'
and has a dependency to @ngrx/store
.
It supports:
✅ Well-known NgRx Store Actions
✅ Global Action dispatch()
✅ Angular Lazy Loading
✅ Auto-generated provideNamedStore()
& injectNamedStore()
Functions
✅ Global Action to Store Method Mappers \
1export const FlightStore = signalStore( 2 // State 3 withEntities({ entity: type<Flight>(), collection: 'flight' }), 4 withEntities({ entity: type<number>(), collection: 'hide' }), 5 // Selectors 6 withComputed(({ flightEntities, hideEntities }) => ({ 7 filteredFlights: computed(() => flightEntities() 8 .filter(flight => !hideEntities().includes(flight.id))), 9 flightCount: computed(() => flightEntities().length), 10 })), 11 // Updater 12 withMethods(store => ({ 13 setFlights: (state: { flights: Flight[] }) => patchState(store, 14 setAllEntities(state.flights, { collection: 'flight' })), 15 updateFlight: (state: { flight: Flight }) => patchState(store, 16 updateEntity({ id: state.flight.id, changes: state.flight }, { collection: 'flight' })), 17 clearFlights: () => patchState(store, 18 removeAllEntities({ collection: 'flight' })), 19 })), 20 // Effects 21 withMethods((store, flightService = inject(FlightService)) => ({ 22 loadFlights: reduxMethod<FlightFilter, { flights: Flight[] }>(pipe( 23 switchMap(filter => from( 24 flightService.load({ from: filter.from, to: filter.to }) 25 )), 26 map(flights => ({ flights })), 27 ), store.setFlights), 28 })), 29);
1export const ticketActions = createActionGroup({ 2 source: 'tickets', 3 events: { 4 'flights load': props<FlightFilter>(), 5 'flights loaded': props<{ flights: Flight[] }>(), 6 'flights loaded by passenger': props<{ flights: Flight[] }>(), 7 'flight update': props<{ flight: Flight }>(), 8 'flights clear': emptyProps() 9 } 10});
1export const { provideFlightStore, injectFlightStore } = 2 createReduxState('flight', FlightStore, store => withActionMappers( 3 mapAction( 4 // Filtered Action 5 ticketActions.flightsLoad, 6 // Side-Effect 7 store.loadFlights, 8 // Result Action 9 ticketActions.flightsLoaded), 10 mapAction( 11 // Filtered Actions 12 ticketActions.flightsLoaded, ticketActions.flightsLoadedByPassenger, 13 // State Updater Method (like Reducers) 14 store.setFlights 15 ), 16 mapAction(ticketActions.flightUpdate, store.updateFlight), 17 mapAction(ticketActions.flightsClear, store.clearFlights), 18 ) 19 );
1export const appRoutes: Route[] = [ 2 { 3 path: 'flight-search-redux-connector', 4 providers: [provideFlightStore()], 5 component: FlightSearchReducConnectorComponent 6 }, 7];
1@Component({ 2 standalone: true, 3 imports: [ 4 JsonPipe, 5 RouterLink, 6 FormsModule, 7 FlightCardComponent 8 ], 9 selector: 'demo-flight-search-redux-connector', 10 templateUrl: './flight-search.component.html', 11}) 12export class FlightSearchReducConnectorComponent { 13 private store = injectFlightStore(); 14 15 protected flights = this.store.flightEntities; 16 17 protected search() { 18 this.store.dispatch( 19 ticketActions.flightsLoad({ 20 from: this.localState.filter.from(), 21 to: this.localState.filter.to() 22 }) 23 ); 24 } 25 26 protected reset(): void { 27 this.store.dispatch(ticketActions.flightsClear()); 28 } 29}
Yes, please! We are always looking for new ideas and contributions.
Since we don't want to bloat the library, we are very selective about new features. You also have to provide the following:
This project uses pnpm to manage dependencies and run tasks (for local development and CI).
Please create an issue. Very likely, we are able to cherry-pick the feature into the lower version.
No vulnerabilities found.
No security vulnerabilities found.