facebook

State Management in Angular : A Quick Guide

Calender

29th July 2024

Clock

13 min read

Author
Richa Kumari

Sr. Associate Consultant L2- Frontend Development

Angular applications require careful state management to guarantee maintainability, scalability, and consistency. Having effective state management keeps your app efficient and well-organized. This tutorial covers the fundamental techniques and resources for Angular state management. If you are looking to develop a web or a mobile application, visit our app development services for more information. 
 

The Significance of State Management 

 

State management is essential for the following reasons
 

1. Performance - Performance is enhanced by reducing unnecessary updates

2. Consistency - Establishing consistency throughout the application's

3. Maintainability - Allows code management and debugging easier

4. Scalability - Makes feature addition easier without requiring complicated reworking

 

Also, Explore | Essentials of Efficient UI/UX Design in Mobile App Development

 

Angular State Management Strategies

 

1. Component State 

 

Often, component-level state management is adequate for straightforward applications. Every element retains its current state on its own.


Example-

 

Create a component e.g - "counter-example"
 

counter-example.ts
@Component({
 selector: 'app-counter-example',
 template: `
{{ count }}
` }) export class CounterExampleComponent { _count = 0; increment() { this._count++; } }

 

2. Service-oriented State Management

 

As your application grows, using services to manage the state becomes important and useful. Services keep and manage the state, acting as a single place where all the data is stored and handled.


Example-

 

Create a service "counter.service.ts"
 

counter.service.ts
@Injectable({
 providedIn: 'root'
})
export class CounterService {
 private _count = 0;
 increment() {
   this._count++;
 }
 getCount() {
   return this._count;
 }
}

 

You may also like |   Native vs. Hybrid vs. Web | Choosing Mobile App Development

 

3. NgRx 

 

Redux-inspired, NgRx is a feature-rich state management library for Angular. It combines reducers, actions, and effects to accurately handle state transitions.

 

Let's jump into the process of implementing NgRx- 
 

1. Installation:
 

ng add @ngrx/store
ng add @ngrx/effects


2. Create Action:
 

Create a component "counter.actions.ts"
 

ng g c counter-actions
import { Component, OnInit } from '@angular/core';
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter] Increment');
export const reset = createAction('[Counter] Reset');

 

3. Create Reducer:
 

Create a file "counter.reducer.ts"
 

import { Component, OnInit } from '@angular/core';
import { createReducer, on } from '@ngrx/store';
import { increment, reset } from '../counter-actions/counter-actions.component';
export const initialState = 0;
const _counterReducer = createReducer(
initialState,
on(increment, state => state + 1),
on(reset, state => 0)
);
export function counterReducer(state: any, action: any) {
return _counterReducer(state, action);
}
 

 

4. Set Up Store:


Modify "app.module.ts" to include the store and reducer
 


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { AppComponent } from './app.component';
import { counterReducer } from './counter.reducer';
@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   StoreModule.forRoot({ count: counterReducer }),
   StoreDevtoolsModule.instrument({ maxAge: 25 })
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

 

5. Create your component with the desired name:
 

Create "counter.component.ts"
 

import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { increment, reset } from './counter.actions';
@Component({
 selector: 'app-counter',
 templateUrl: './counter.component.html',
})
export class CounterComponent {
 count$ = this.store.select('count');
 constructor(private store: Store<{ count: number }>) {}
 increment() {
   this.store.dispatch(increment());
 }
 reset() {
   this.store.dispatch(reset());
 }
}


6. Create HTML file:

 

In your "counter.component.html" file
 

Counter: {{ count$ | async }}


7. Use the Component: 

 

Include selector in app.component.html.
 

 

Also, Explore | Cloud-based App Development | A Quintessential Guide

 

In summary


Angular's state management techniques can vary depending on how sophisticated your application is. Services or component states could be sufficient for small apps. NgRx or NGXS offer strong solutions for larger applications. Try out these choices to see which one best fits your requirements. If you are looking for app development services, connect with blockchain developers to get started. 

Author Richa Kumari

Richa is a efficient frontend developer with expertise in Angular and experience in developing and maintaining complex web applications. She has a solid understanding of front-end development, including TypeScript, HTML, CSS, and JavaScript. Currently, she is expanding her skill set by learning ReactJS. Richa has worked on various projects, including Rafa, Wethio Properties, Hedgex Exchange, and DSwapper, where she was responsible for designing and implementing user-friendly interfaces, ensuring efficient performance, and ensuring the overall quality of the code. She has excellent communication skills and works effectively with her team members to ensure that the final product meets the client's requirements.

Sr. Associate Consultant L2- Frontend Development

bg bg

What's Trending in Tech

bg

Our Offices

India

INDIA

DG-18-009, Tower B,
Emaar Digital Greens, Sector 61,
Gurugram, Haryana
122011.
Unit- 117-120, First Floor,
Welldone Tech Park,
Sector 48, Sohna road,
Gurugram, Haryana
122018.
USA

USA

30N, Gloud St STR E, Sheridan, Wyoming (USA) - 82801
Singapore

SINGAPORE

10 Anson Road, #13-09, International Plaza Singapore 079903.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.