Angular state management NgRx | Live Session

3 min read 6 months ago
Published on Aug 30, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial provides a step-by-step guide on implementing state management in Angular using NgRx. It focuses on creating a store to handle a simple counter application. Understanding NgRx is essential for managing complex state in Angular applications, making it easier to maintain and debug.

Step 1: Setting Up Your Angular Environment

  • Install Angular CLI: Make sure you have the Angular CLI installed. You can do this via npm:
    npm install -g @angular/cli
    
  • Create a New Angular Project: Use the following command to create a new project:
    ng new ngrx-counter
    
  • Navigate to the Project Directory:
    cd ngrx-counter
    

Step 2: Installing NgRx

  • Add NgRx to Your Project: Install the necessary NgRx packages using npm:
    ng add @ngrx/store @ngrx/store-devtools
    
  • Understand the Structure: NgRx uses actions, reducers, selectors, and effects to manage the state. Familiarize yourself with these concepts.

Step 3: Creating the Counter Store

  • Create a Counter Folder: Inside your src/app directory, create a folder named counter.
  • Create Actions: In the counter folder, create a file named counter.actions.ts and define your actions:
    import { createAction } from '@ngrx/store';
    
    export const increment = createAction('[Counter Component] Increment');
    export const decrement = createAction('[Counter Component] Decrement');
    export const reset = createAction('[Counter Component] Reset');
    

Step 4: Setting Up the Reducer

  • Create Reducer File: Create a file named counter.reducer.ts in the counter folder and define the reducer:
    import { createReducer, on } from '@ngrx/store';
    import { increment, decrement, reset } from './counter.actions';
    
    export const initialState = 0;
    
    const _counterReducer = createReducer(
      initialState,
      on(increment, state => state + 1),
      on(decrement, state => state - 1),
      on(reset, () => initialState)
    );
    
    export function counterReducer(state, action) {
      return _counterReducer(state, action);
    }
    

Step 5: Registering the Store Module

  • Import Store Module: Open app.module.ts and register the counter reducer:
    import { StoreModule } from '@ngrx/store';
    import { counterReducer } from './counter/counter.reducer';
    
    @NgModule({
      imports: [
        StoreModule.forRoot({ count: counterReducer }),
        // other imports
      ],
      // declarations, providers, bootstrap
    })
    export class AppModule { }
    

Step 6: Creating the Component

  • Generate Counter Component: Use Angular CLI to create a new component:
    ng generate component counter
    
  • Implement Component Logic: In counter.component.ts, connect to the store and dispatch actions:
    import { Component } from '@angular/core';
    import { Store } from '@ngrx/store';
    import { increment, decrement, reset } from '../counter/counter.actions';
    import { Observable } from 'rxjs';
    
    @Component({
      selector: 'app-counter',
      templateUrl: './counter.component.html'
    })
    export class CounterComponent {
      count$: Observable<number>;
    
      constructor(private store: Store<{ count: number }>) {
        this.count$ = store.select('count');
      }
    
      increment() {
        this.store.dispatch(increment());
      }
    
      decrement() {
        this.store.dispatch(decrement());
      }
    
      reset() {
        this.store.dispatch(reset());
      }
    }
    

Step 7: Designing the Component Template

  • Create the Template: In counter.component.html, add the following code to create a simple UI:
    <h1>Counter: {{ count$ | async }}</h1>
    <button (click)="increment()">Increment</button>
    <button (click)="decrement()">Decrement</button>
    <button (click)="reset()">Reset</button>
    

Conclusion

You have successfully set up a basic Angular application with state management using NgRx. By following these steps, you've created a store for a counter, allowing you to increment, decrement, and reset the counter value.

Next Steps

  • Explore more advanced features of NgRx like effects and selectors.
  • Consider building more complex applications using NgRx to manage state effectively.
  • Check out additional resources or tutorials to deepen your understanding of state management in Angular.