A simple way to create signal stores with a read-only interface.
| ngx-simple-signal-store | Angular |
|---|---|
| 3.x | >= 20 |
| 2.x | 19.x.x |
| 1.x | 18.x.x |
npm install ngx-simple-signal-store # Or if you use yarn yarn add ngx-simple-signal-storeAdd the store provider with an initial state and a unique token to your app.config.ts as a provider:
import { createInjectionToken, provideStore } from 'ngx-simple-signal-store'; export interface DemoState { theAnswerToLife: number; } export const initialDemoState: DemoState = { theAnswerToLife: 42 }; export const demoStateToken = createInjectionToken<DemoState>(); export const appConfig: ApplicationConfig = { providers: [ provideStore(initialDemoState, demoStateToken), ], };Then, import and inject it into your components:
import { demoStateToken } from './app.config.ts'; @Component({}) export class DemoComponent { readonly #demoStore = inject(demoStateToken); }Add the store provider with an initial state and a unique token to your component as a provider:
import { createInjectionToken, provideStore } from 'ngx-simple-signal-store'; export interface DemoComponentState { theAnswerToEverything: number; } export const initialDemoComponentState: DemoComponentState = { theAnswerToEverything: 42 }; export const demoComponentStateToken = createInjectionToken<DemoComponentState>(); @Component({ providers: [provideStore(initialDemoComponentState, demoComponentStateToken)] }) export class DemoComponent { readonly #demoComponentStore = inject(demoComponentStateToken); }T is the type of the state.
const cookieExists: boolean = demoStore.state;Return with the readonly state. The returned object keys are the referenced state keys, and the values are the read-only signals.
demoStore.setState('key', 0);Sets the state with a specified key and value.
// primitive: demoStore.patchState('key', 0); // The value before patch: 1 // The value after patch: 0 // array: demoStore.patchState('key', [3]); // The value before patch: [1, 2] // The value after patch: [1, 2, 3] // object: demoStore.patchState('key', {value: 0}); // The value before patch: {value: 1} // The value after patch: {value: 0}Patch the state with a specified key and value.
A callback function can be used for the complex operations:
demoStore.patchState('key', state => ({value: state.value + 1}));demoStore.resetStore();Reset the store to the initial state.