Angular 18 state management using NGXS | Angular NGxS state management tutorial in Hindi

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 will guide you through managing state in an Angular application using NGXS, a powerful state management library. We will cover the basics of NGXS, its setup in Angular, and practical implementations, making it easier to manage application state effectively.

Step 1: Understanding NGXS

  • NGXS is a state management library for Angular applications.
  • It simplifies state management and improves performance by using a single source of truth.
  • Key benefits include:
    • Predictable state management
    • Easy debugging and testing
    • Improved performance with less boilerplate code

Step 2: Setting Up Angular and NGXS

  1. Create a new Angular project if you don't have one:
    ng new my-ngxs-app
    cd my-ngxs-app
    
  2. Install NGXS in your project:
    npm install @ngxs/store
    
  3. Import NGXS into your application:
    • Open app.module.ts and add the following import:
      import { NgxsModule } from '@ngxs/store';
      
    • Include NGXS in your imports array:
      @NgModule({
        imports: [
          NgxsModule.forRoot([]), // Initialize with an empty state
        ],
      })
      

Step 3: Creating State

  1. Define a state model to represent your application's data. For example:
    export interface MyStateModel {
      count: number;
    }
    
  2. Create a state class:
    import { State, Action, StateContext } from '@ngxs/store';
    
    @State<MyStateModel>({
      name: 'myState',
      defaults: {
        count: 0,
      },
    })
    export class MyState {
      @Action(Increment)
      increment(ctx: StateContext<MyStateModel>) {
        const state = ctx.getState();
        ctx.setState({ count: state.count + 1 });
      }
    }
    
  3. Register the state in app.module.ts:
    imports: [
      NgxsModule.forRoot([MyState]),
    ],
    

Step 4: Selecting Data from the Store

  • Use selectors to access state data:
    import { Selector } from '@ngxs/store';
    
    export class MyState {
      // Existing code...
    
      @Selector()
      static getCount(state: MyStateModel) {
        return state.count;
      }
    }
    

Step 5: Using Memoized Selectors

  • Memoized selectors optimize performance by caching results:
    @Selector([MyState.getCount])
    static isEvenCount(count: number) {
      return count % 2 === 0;
    }
    

Step 6: Iterating with Observables

  • Use Angular's *ngFor to iterate over observable data:
    <div *ngFor="let item of items$ | async">
      {{ item }}
    </div>
    

Step 7: Creating Dynamic Selectors

  • Dynamic selectors allow fetching data based on parameters:
    @Selector()
    static getItemById(state: MyStateModel, id: number) {
      return state.items.find(item => item.id === id);
    }
    

Step 8: Understanding selectSignal and Zoneless Change Detection

  • NGXS supports selectSignal for better performance:
    • Use selectSignal to reduce unnecessary component re-renders.

Step 9: Creating a Bucket State

  • Create a bucket state for grouping related data:
    interface BucketStateModel {
      buckets: Bucket[];
    }
    
    @State<BucketStateModel>({
      name: 'bucketState',
      defaults: {
        buckets: [],
      },
    })
    

Step 10: Handling Actions

  • Define an action to modify state:
    export class AddBucket {
      static readonly type = '[Bucket] Add';
      constructor(public payload: Bucket) {}
    }
    
    @Action(AddBucket)
    addBucket(ctx: StateContext<BucketStateModel>, action: AddBucket) {
      const state = ctx.getState();
      ctx.setState({ buckets: [...state.buckets, action.payload] });
    }
    

Step 11: Async Actions in NGXS

  • Implement async actions using NGXS:
    @Action(LoadBuckets)
    async loadBuckets(ctx: StateContext<BucketStateModel>) {
      const buckets = await fetch('/api/buckets').then(res => res.json());
      ctx.setState({ buckets });
    }
    

Conclusion

In this tutorial, you learned how to set up and utilize NGXS for state management in Angular applications. We covered key concepts, including creating state, selecting data, and handling asynchronous actions.

Next steps include exploring more advanced features of NGXS and integrating it into larger Angular applications. For further practice, consider visiting the provided GitHub repository for example code or developing your own state management scenarios.