Search code examples
angularngxsangular-standalone-components

How to use Ngxs in a standalone component?


Is it possible to use Ngxs in a standalone component? I've tried importing the NgxsModule in the following ways:

@Component({
  ...
  imports: [
    ...
    NgxsModule.forFeature([MyState]),
...

and

@Component({
  ...
  imports: [
    ...
    NgxsModule.forRoot([MyState]),
...

But both give me the following error message: Type 'ModuleWithProviders<NgxsFeatureModule>' is not assignable to type 'any[] | Type<any>' (or NgxsRootModule in the forRoot case). A more in-depth error message is available as well: 'imports' contains a ModuleWithProviders value, likely the result of a 'Module.forRoot()'-style call. These calls are not used to configure components and are not valid in standalone component imports - consider importing them in the application bootstrap instead.

Is this supported and I have the syntax wrong? Or is this not supported? If not supported, what's the blocker?


Solution

  • yes it is supported.

    As you can see in the Angular standalone component guide:

    The standalone bootstrap operation is based on explicitly configuring a list of Providers for dependency injection. However, existing libraries may rely on NgModules for configuring DI. For example, Angular’s router uses the RouterModule.forRoot() helper to set up routing in an application.

    So you can solve the problem in the same way as they solve it for the router. Edit the app.config.ts file:

    bootstrapApplication(AppComponent, {
      providers: [
          importProvidersFrom(NgxsModule.forRoot([MyState])),
        // ...
      ]
    });