Skip to main content

Command Palette

Search for a command to run...

NgRx Standalone API

Updated
NgRx Standalone API

In this article, I'll show how to use NgRx with Angular Standalone API. If you're not familiar with it, please refer to the https://barcioch.pro/angular-standalone-components-directives-pipes article. The following examples show how to define a store using NgModule and standalone api. It's not a NgRx usage guide, since I'll cover it in a different article.

NgRx with NgModule

Root store

The root store is usually defined in the main AppModule. The forRoot method is used so the whole app can access it.

@NgModule({
  imports: [
    StoreModule.forRoot({ router: routerReducer, authReducer: authReducer }),
    EffectsModule.forRoot([AuthEffects]),
    StoreRouterConnectingModule.forRoot(),
    StoreDevtoolsModule.instrument()
  ]
})

Feature store

When dealing with the feature modules I'm using forFeature method.

@NgModule({
  imports: [
    StoreModule.forFeature('featureKey', featureReducer),
    EffectsModule.forFeature([FeatureEffects]),
  ]
})

NgRx with standalone api

Root store

The root store should be defined within bootstrapApplication function. The store will be provided in the providers instead of NgModule.imports. The equivalents:

  • StoreModule.forRoot() -> provideStore()

  • EffectsModule.forRoot() -> provideEffects()

  • StoreRouterConnectingModule.forRoot() -> provideRouterStore()

  • StoreDevtoolsModule.instrument() -> provideStoreDevtools()

bootstrapApplication(AppComponent, {
  providers: [
    provideStore({ router: routerReducer, auth: AuthReducer }),
    provideEffects([AuthEffects]),
    provideRouterStore(),
    provideStoreDevtools(),
  ]
});

Feature store

The feature store has to be defined within the route providers instead of NgModule.imports. The equivalents:

  • StoreModule.forFeature() -> provideStoreFeature()

  • EffectsModule.forFeature() -> provideFeatureEffects()

export const featureRoutes: Route[] = [
  {
    path: '',
    providers: [
      provideStoreFeature('feature', featureReducer),
      provideFeatureEffects([FeatureEffects]),
    ],
  },
];

That's all. Using NgRx standalone api is very simple and the functions are self-explanatory.