Planning project structure
I’m thinking about how to make this project setup concise yet effective. I’ll organize the content into sections, using bullet lists and key code snippets. It’s clear I can skip some boilerplate and mention that I'm omitting imports for brevity.
Starting with the project setup, I'll cover installing NgRx and DevTools, app and store configuration, creating a lazy-loaded feature module for 'Products,' modeling state with NgRx, and discussing advanced concepts like router store and meta-reducers at the end.Setting up NgRx with Router Store
I'm planning to add the router-store at the root of the application and ensure the code is accurate. The initial CLI commands will be crucial, starting with creating an Angular app with routing and SCSS styles. I’ll run commands for NgRx, including store, effects, store-devtools, and router-store.
Using ng add is convenient because it automates imports, but I want to show a manual setup for clarity. I'll define the feature key 'products' and set up an entity adapter along with the actions file using createActionGroup.Defining products actions and state
I'm setting up an action group for managing products. I'll define the actions like 'Load Products,' 'Load Products Success,' and 'Load Products Failure' using createActionGroup, which makes things neat and organized.
Now for the reducer, the feature key will be 'products,' and I’ll set up the ProductsState interface to extend EntityState<Product>, including loading and error states. Using createEntityAdapter, I'll establish an initial state where loading is false and error is null.
Then I'll create a feature reducer that handles the loading process and reflects success or failure. I should remember that createFeature automates selectors, so it’s important to use those. For the feature module, I'll go with StoreModule.forFeature(productsFeature) to keep things modern and in line with NgRx 15+.Implementing Products Effects and Component
I'm setting up the ProductsEffects class to manage loading products from the API. Using createEffect, I'll listen for ProductsActions.loadProducts, and when triggered, it will call the HTTP service to fetch products. On success, it dispatches loadProductsSuccess, and any errors will trigger loadProductsFailure.
Next, in the ProductsModule, I'll declare the ProductsListComponent and import the necessary modules. The routing will define a simple path leading to the products list.
The ProductsListComponent will handle displaying products, errors, and loading states by combining observables. However, I still need to define the selectors selectProductsLoading and selectProductsError.Creating Selectors and App Setup
I’m working on the selectors by creating a file that includes key selectors like selectProductsLoading and selectProductsError, which will help manage product state. Next, I'll set up the app's routing module to redirect to products and load the ProductsModule lazily.
In the AppModule, I’ll declare the main app component and import essential Angular modules. It’s important to adjust the logOnly setting to use !isDevMode() for simplicity. I should mention how lazy loading interacts with the root store, but we can skip testing instructions for now. I'll ensure to provide a clear step-by-step guide! Below is a complete, opinionated example of an Angular app that uses:
- NgRx for advanced state management (actions, reducers, selectors, effects, Entity)
- Lazy-loaded feature module with its own feature store
The example is a simple “Products” list loaded from a (fake) API.
1. Create the Angular project
npm install -g @angular/cli
ng new ngrx-lazy-app --routing --style=scss
cd ngrx-lazy-app
2. Install NgRx
Install core NgRx packages:
npm install @ngrx/store @ngrx/effects @ngrx/store-devtools @ngrx/router-store @ngrx/entity
3. Root setup: AppModule + Store
src/app/app.module.ts
import { NgModule, isDevMode } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { StoreRouterConnectingModule } from '@ngrx/router-store';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
// Root NgRx store (no root reducers yet)
StoreModule.forRoot({}, {}),
// Root effects (none yet)
EffectsModule.forRoot([]),
// Time-travel debugging
StoreDevtoolsModule.instrument({
maxAge: 25,
logOnly: !isDevMode(),
}),
// Sync Angular Router state into Store
StoreRouterConnectingModule.forRoot(),
],
bootstrap: [AppComponent],
})
export class AppModule {}
4. Root routing with lazy-loaded feature
We’ll lazy-load a ProductsModule at /products.
src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'products', pathMatch: 'full' },
{
path: 'products',
loadChildren: () =>
import('./products/products.module').then(m => m.ProductsModule),
},
// { path: '**', redirectTo: 'products' } // optional wildcard
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
5. Create the lazy-loaded Products feature module
ng g module products --route products --module app-routing.module.ts
# (If Angular CLI already added the lazy route, adjust as needed)
ng g component products/components/products-list --module products
Make sure the generated routing module is simple:
src/app/products/products-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ProductsListComponent } from './components/products-list/products-list.component';
const routes: Routes = [
{
path: '',
component: ProductsListComponent,
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class ProductsRoutingModule {}
src/app/products/products.module.ts
We’ll hook NgRx feature store here (later we’ll add the feature definition).
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductsRoutingModule } from './products-routing.module';
import { ProductsListComponent } from './components/products-list/products-list.component';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { productsFeature } from './store/products.reducer';
import { ProductsEffects } from './store/products.effects';
@NgModule({
declarations: [ProductsListComponent],
imports: [
CommonModule,
ProductsRoutingModule,
// Feature-level NgRx registrations
StoreModule.forFeature(productsFeature),
EffectsModule.forFeature([ProductsEffects]),
],
})
export class ProductsModule {}
Note: StoreModule.forFeature(productsFeature) uses the NgRx createFeature API.
6. Define the Products feature state
Create a small store folder:
mkdir -p src/app/products/store
6.1 Model
src/app/products/store/products.models.ts
export interface Product {
id: number;
name: string;
price: number;
}
6.2 Actions
src/app/products/store/products.actions.ts
import { createActionGroup, emptyProps, props } from '@ngrx/store';
import { Product } from './products.models';
export const ProductsActions = createActionGroup({
source: 'Products',
events: {
'Load Products': emptyProps(),
'Load Products Success': props<{ products: Product[] }>(),
'Load Products Failure': props<{ error: string }>(),
},
});
6.3 Reducer + Feature (using Entity)
src/app/products/store/products.reducer.ts
import { createFeature, createReducer, on } from '@ngrx/store';
import { createEntityAdapter, EntityState } from '@ngrx/entity';
import { ProductsActions } from './products.actions';
import { Product } from './products.models';
export const productsFeatureKey = 'products';
export interface ProductsState extends EntityState<Product> {
loading: boolean;
error: string | null;
}
export const productsAdapter = createEntityAdapter<Product>({
selectId: product => product.id,
});
const initialState: ProductsState = productsAdapter.getInitialState({
loading: false,
error: null,
});
const reducer = createReducer(
initialState,
on(ProductsActions.loadProducts, state => ({
...state,
loading: true,
error: null,
})),
on(ProductsActions.loadProductsSuccess, (state, { products }) =>
productsAdapter.setAll(products, {
...state,
loading: false,
error: null,
}),
),
on(ProductsActions.loadProductsFailure, (state, { error }) => ({
...state,
loading: false,
error,
})),
);
// createFeature gives us reducer + basic selectors
export const productsFeature = createFeature({
name: productsFeatureKey,
reducer,
});
export const {
name: featureName, // 'products'
reducer: productsReducer, // for older APIs if needed
selectProductsState, // root selector for feature
selectIds,
selectEntities,
selectAll,
selectTotal,
} = productsFeature;
6.4 Selectors
src/app/products/store/products.selectors.ts
import { createSelector } from '@ngrx/store';
import { productsFeature } from './products.reducer';
export const {
selectProductsState,
selectAll: selectAllProducts,
} = productsFeature;
export const selectProductsLoading = createSelector(
selectProductsState,
state => state.loading,
);
export const selectProductsError = createSelector(
selectProductsState,
state => state.error,
);
6.5 Effects
src/app/products/store/products.effects.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, map, of, switchMap } from 'rxjs';
import { ProductsActions } from './products.actions';
import { Product } from './products.models';
@Injectable()
export class ProductsEffects {
loadProducts$ = createEffect(() =>
this.actions$.pipe(
ofType(ProductsActions.loadProducts),
switchMap(() =>
// Replace with your real API endpoint
this.http.get<Product[]>('/api/products').pipe(
map(products => ProductsActions.loadProductsSuccess({ products })),
catchError(err =>
of(
ProductsActions.loadProductsFailure({
error: err.message ?? 'Failed to load products',
}),
),
),
),
),
),
);
constructor(private actions$: Actions, private http: HttpClient) {}
}
For a quick demo, you can point to a public fake API (e.g. https://fakestoreapi.com/products) or mock the backend.
7. Products component using feature store
src/app/products/components/products-list/products-list.component.ts
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { combineLatest, map, Observable } from 'rxjs';
import { ProductsActions } from '../../store/products.actions';
import {
selectAllProducts,
selectProductsLoading,
selectProductsError,
} from '../../store/products.selectors';
import { Product } from '../../store/products.models';
interface ProductsViewModel {
products: Product[];
loading: boolean;
error: string | null;
}
@Component({
selector: 'app-products-list',
templateUrl: './products-list.component.html',
styleUrls: ['./products-list.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductsListComponent implements OnInit {
vm$: Observable<ProductsViewModel> = combineLatest([
this.store.select(selectAllProducts),
this.store.select(selectProductsLoading),
this.store.select(selectProductsError),
]).pipe(
map(([products, loading, error]) => ({ products, loading, error })),
);
constructor(private store: Store) {}
ngOnInit(): void {
// trigger load on first visit to lazy-loaded module
this.store.dispatch(ProductsActions.loadProducts());
}
}
src/app/products/components/products-list/products-list.component.html
<ng-container *ngIf="vm$ | async as vm">
<div *ngIf="vm.loading">Loading products...</div>
<div *ngIf="vm.error" class="error">
Error: {{ vm.error }}
</div>
<ul *ngIf="!vm.loading && !vm.error">
<li *ngFor="let product of vm.products">
<strong>{{ product.name }}</strong>
– {{ product.price | currency }}
</li>
</ul>
</ng-container>
8. What you now have (architecturally)
- Lazy-loaded feature module (
ProductsModule).
- Feature-level store registered only when that module is loaded:
StoreModule.forFeature(productsFeature)
EffectsModule.forFeature([ProductsEffects])
- Advanced state management:
- Entity adapter (
createEntityAdapter) for normalized collections.
- Side effects with
createEffect to call APIs.
- Slice-specific selectors composed into a view model.
- Global tooling:
- Store DevTools and Router Store integrated at root.
9. Run the app
ng serve
Navigate to http://localhost:4200/products.
If you share your Angular version and whether you prefer module-based or standalone APIs, I can adapt this to the latest standalone provideStore/provideEffects style as well.