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?
We got new methods and this functionality is now documented! 🚀
use provideStore() as seen in documentation:
https://www.ngxs.io/introduction/installation#manual-installation
In short:
export const appConfig: ApplicationConfig = {
providers: [provideStore()]
};
use provideStates, as seen in documentation: https://www.ngxs.io/concepts/state/lazy
in short for route:
export const routes: Routes = <Routes>[
{
path: '',
component: AnimalsComponent,
providers: [provideStates([AnimalsState])]
}
];
You can use importProvidersFrom() from '@angular/core' NgxsModule.forRoot() inside your bootstrap function (same as SilasDerProfi wrote before me)
Inside your main.ts:
bootstrapApplication(
AppComponent,
{
providers: [
importProvidersFrom(
NgxsModule.forRoot(
[MyState, SidebarState, CoreState],
{
developmentMode: !environment.production,
selectorOptions: {
suppressErrors: false,
injectContainerState: false
}
}
),
NgxsResetPluginModule.forRoot(),
// devtools always last
NgxsReduxDevtoolsPluginModule.forRoot()
)
]
}
).catch(err => console.error(err));
You can set your lazy Loaded forFeature([FooState]) while you are declaring your routes.
See official documentation, or there is an example of lazy loaded routes:
import { importProvidersFrom } from '@angular/core';
export default <Routes>[
{
path: '',
loadComponent:
() => import('./foo-list/foo-list.component')
.then(mod => mod.FooListComponent),
providers: [
importProvidersFrom(
NgxsModule.forFeature([FooOverviewState])
)
]
},
{
path: 'add',
loadComponent:
() => import('./foo-item-add/foo-item-add.component')
.then(mod => mod.FooItemAddComponent),
providers: [
importProvidersFrom(
NgxsModule.forFeature([FooState])
)
]
},
{
path: ':id',
loadComponent:
() => import('./foo-item-edit/foo-item-edit.component')
.then(mod => mod.FooItemEditComponent),
providers: [
importProvidersFrom(
NgxsModule.forFeature([FooState])
)
]
}
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With