Build an Angular application using NgRx for advanced state management and lazy loading.
- User
Build an Angular application using NgRx for advanced state management and lazy loading.
Assistant
Analyzing the Angular App
I'm currently focused on the overarching objective: crafting an Angular application with NgRx and lazy loading. I've broken it down into actionable steps. The goal is clear, the requirements have been identified, and I'm beginning to define the architecture. Next, I'll dive into module organization.
Outlining the Application Structure
I'm now detailing the architectural blueprint. I'm setting up the application root with
AppComponentandAppConfig. I'll establish core and shared modules, like models and services, for product management. Also, I'm defining the root state. Next, I will delve into the lazy-loadedProductsfeature module.Planning the NgRx Implementation
I'm now deep in the NgRx details. I've broken down the steps, starting with installation. I'm focusing on defining actions and how they trigger effects. Then the reducer, using the
@ngrx/entityadapter for efficient state management of products. The feature state design is my primary focus; I'm mapping out the Actions, Reducers, Effects, and Selectors for theProductsfeature module, especially the best approach for the components that will consume and interact with the data.Detailing the Implementation Steps
I'm now fully immersed in the coding strategy. My focus is on the essential "how-to" elements. This includes determining the precise commands to get everything installed and properly configured, and which APIs to use. I'm focusing on providing the user with detailed code examples. I'll include explanations for each piece, to ensure clarity and ease of use.
Mapping Out the Structure
I'm now fully immersed in the design phase. I've sketched out the application's basic structure and determined the necessary modules. I'm focusing on "Products," the lazy-loaded feature module, which will be the heart of the demo. I'm using the latest Angular's Standalone Component APIs. The
Productmodel, and its service, is next.This guide builds a modern Angular (v17/v18) application using Standalone Components, NgRx, @ngrx/entity, and Lazy Loading with Lazy State Injection.
This approach represents the current "Advanced" standard, moving away from
NgModulesto Functional APIs.Prerequisites
Run the following commands to create the app and install dependencies:
ng new ngrx-advanced-app --standalone --routing cd ngrx-advanced-app npm install @ngrx/store @ngrx/effects @ngrx/entity @ngrx/store-devtools
File Structure
We will build a "Products" feature that is lazy-loaded.
src/app/ ├── core/ ├── products/ (Lazy Feature) │ ├── state/ │ │ ├── product.actions.ts │ │ ├── product.reducer.ts │ │ ├── product.effects.ts │ │ └── product.selectors.ts │ ├── product.model.ts │ ├── product.service.ts │ ├── product.routes.ts (Lazy Entry) │ └── product-list/ │ └── product-list.component.ts ├── app.config.ts (Root Config) └── app.component.ts
Step 1: Domain Model and Service
Create the shape of data and a mock service.
src/app/products/product.model.tsexport interface Product { id: string; name: string; price: number; }src/app/products/product.service.tsimport { Injectable } from '@angular/core'; import { delay, Observable, of } from 'rxjs'; import { Product } from './product.model'; @Injectable({ providedIn: 'root' }) export class ProductService { private mockProducts: Product[] = [ { id: '1', name: 'Angular Mug', price: 15 }, { id: '2', name: 'NgRx T-Shirt', price: 25 }, { id: '3', name: 'RxJS Sticker', price: 5 }, ]; getProducts(): Observable<Product[]> { // Simulate API network latency return of(this.mockProducts).pipe(delay(1000)); } }
Step 2: Advanced State Setup (Feature)
We will use
@ngrx/entity. This is considered "advanced" practice because it normalizes data (stores it like a database hash map) for high performance, rather than a simple array.2.1 Actions
We use
createActionGroupto reduce boilerplate.src/app/products/state/product.actions.tsimport { createActionGroup, emptyProps, props } from '@ngrx/store'; import { Product } from '../product.model'; export class ProductActions { static readonly productApi = createActionGroup({ source: 'Products API', events: { 'Load Products': emptyProps(), 'Load Products Success': props<{ products: Product[] }>(), 'Load Products Failure': props<{ error: string }>(), }, }); }2.2 Reducer (with Entity Adapter)
Here we configure the state shape and how actions modify it.
src/app/products/state/product.reducer.tsimport { createFeature, createReducer, on } from '@ngrx/store'; import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity'; import { Product } from '../product.model'; import { ProductActions } from './product.actions'; // 1. Define State interface consisting of EntityState + extra props export interface ProductState extends EntityState<Product> { isLoading: boolean; error: string | null; } // 2. Create Adapter export const adapter: EntityAdapter<Product> = createEntityAdapter<Product>(); // 3. Define Initial State export const initialState: ProductState = adapter.getInitialState({ isLoading: false, error: null, }); // 4. Create Feature (Automatically handles feature name and selector slicing) export const productsFeature = createFeature({ name: 'products', reducer: createReducer( initialState, on(ProductActions.productApi.loadProducts, (state) => ({ ...state, isLoading: true })), on(ProductActions.productApi.loadProductsSuccess, (state, { products }) => { // adapter.setAll handles the normalization logic return adapter.setAll(products, { ...state, isLoading: false }); }), on(ProductActions.productApi.loadProductsFailure, (state, { error }) => ({ ...state, isLoading: false, error })) ), });2.3 Effects
Handle side effects (API calls) isolated from components.
src/app/products/state/product.effects.tsimport { Injectable, inject } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { catchError, map, switchMap, of } from 'rxjs'; import { ProductService } from '../product.service'; import { ProductActions } from './product.actions'; @Injectable() export class ProductEffects { private actions$ = inject(Actions); private productService = inject(ProductService); loadProducts$ = createEffect(() => this.actions$.pipe( ofType(ProductActions.productApi.loadProducts), switchMap(() => this.productService.getProducts().pipe( map((products) => ProductActions.productApi.loadProductsSuccess({ products })), catchError((error) => of(ProductActions.productApi.loadProductsFailure({ error: error.message })) ) ) ) ) ); }2.4 Selectors
Since we used
createFeature, NgRx generates default selectors automatically. We just need to combine them with the Entity Adapter selectors.src/app/products/state/product.selectors.tsimport { createSelector } from '@ngrx/store'; import { productsFeature, adapter } from './product.reducer'; // Destructure the magic selectors generated by the adapter const { selectAll } = adapter.getSelectors(); // Combine feature state with adapter selectors // 'selectProductsState' is auto-generated by `createFeature` export const selectAllProducts = createSelector( productsFeature.selectProductsState, selectAll ); export const selectProductsLoading = productsFeature.selectIsLoading; export const selectProductsError = productsFeature.selectError;
Step 3: Lazy Loaded Routes (The Advanced Part)
This is crucial. We do not register the product state in
app.config. Instead, we register it inside the routed providers array. This ensures the redux state slice works only when the user visits this route.src/app/products/product.routes.tsimport { Routes } from '@angular/router'; import { provideState } from '@ngrx/store'; import { provideEffects } from '@ngrx/effects'; import { productsFeature } from './state/product.reducer'; import { ProductEffects } from './state/product.effects'; import { ProductListComponent } from './product-list/product-list.component'; export const PRODUCT_ROUTES: Routes = [ { path: '', component: ProductListComponent, providers: [ // Lazy load the state slice provideState(productsFeature), // Lazy load the effects provideEffects(ProductEffects), ], }, ];
Step 4: The Component
Using the
AsyncPipeandStore.src/app/products/product-list/product-list.component.tsimport { Component, OnInit, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Store } from '@ngrx/store'; import { ProductActions } from '../state/product.actions'; import { selectAllProducts, selectProductsLoading } from '../state/product.selectors'; @Component({ selector: 'app-product-list', standalone: true, imports: [CommonModule], template: ` <h2>Product List (Lazy Loaded)</h2> <div *ngIf="isLoading$ | async">Loading products...</div> <ul *ngIf="!(isLoading$ | async)"> <li *ngFor="let product of products$ | async"> {{ product.name }} - \${{ product.price }} </li> </ul> <button (click)="reload()">Reload</button> `, }) export class ProductListComponent implements OnInit { private store = inject(Store); products$ = this.store.select(selectAllProducts); isLoading$ = this.store.select(selectProductsLoading); ngOnInit() { this.store.dispatch(ProductActions.productApi.loadProducts()); } reload() { this.store.dispatch(ProductActions.productApi.loadProducts()); } }
Step 5: Root Application Configuration
Wire up the Router and the Root Store.
src/app/app.routes.tsimport { Routes } from '@angular/router'; export const routes: Routes = [ { path: 'products', // Lazy loading syntax for Standalone Routes loadChildren: () => import('./products/product.routes').then((m) => m.PRODUCT_ROUTES), }, ];src/app/app.config.tsimport { ApplicationConfig, isDevMode } from '@angular/core'; import { provideRouter } from '@angular/router'; import { provideStore } from '@ngrx/store'; import { provideEffects } from '@ngrx/effects'; import { provideStoreDevtools } from '@ngrx/store-devtools'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), // Initialize Root Store (empty, features are added lazily) provideStore(), provideEffects(), // Enable Redux DevTools provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }), ], };src/app/app.component.tsimport { Component } from '@angular/core'; import { RouterLink, RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet, RouterLink], template: ` <nav> <a routerLink="/">Home</a> | <a routerLink="/products">Products (Lazy)</a> </nav> <hr /> <router-outlet></router-outlet> ` }) export class AppComponent {}
How to Test
- Start the app:
ng serve - Open Browser: Go to
http://localhost:4200. - Open Redux DevTools: (Install the Chrome extension).
- Initially, you will see the store is empty.
- Click "Products":
- Angular downloads the chunk
products/product.routes. - NgRx: You will see
[Store] @ngrx/store/inithappen again or specifically forproducts. - Action:
[Products API] Load Productstriggers. - UI: Displays "Loading products...".
- Action:
[Products API] Load Products Successtriggers. - UI: Displays the list.
- Angular downloads the chunk
Why is this "Advanced"?
- Standalone APIs: Uses
provideStore()andprovideState()instead ofStoreModule.forRoot/forFeature. - Entity Adapter: The state isn't an array; it's an object dictionary (
{ "1": {id: "1", ...} }). This is O(1) access speed and prevents duplicates, which is standard for enterprise apps. - Action Groups: Uses the specific Angular 14+ syntax (
createActionGroup) to cleanly namespace actions. - Lazy State Injection: The
productsstate slice does not exist in the Store until the user actually navigates to the route, saving memory and initial bundle size.
- Start the app:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.