NgRx Product Management

NgRx is a powerful state management library for Angular applications. This example demonstrates how to manage a list of products (create, edit, and delete) using NgRx.

Install from NPM

Install NgRx library from the command prompt in the root directory of the project:


                        ng add @ngrx/store @ngrx/effects @ngrx/store-devtools

After installation, NgRx will automatically configure your application.

Setting Up State Management

Create a new state file to manage your application's product state:


                        // src/app/state/product.state.ts
export interface Product {
    id: number;
    name: string;
    price: number;
}

export interface AppState {
    products: Product[];
}
                    
Creating Actions

Create a file for product actions:


                        // src/app/state/product.actions.ts
import { createAction, props } from '@ngrx/store';
import { Product } from './product.state';

export const addProduct = createAction('[Product API] Add Product', props<{ product: Product }>());
export const editProduct = createAction('[Product API] Edit Product', props<{ product: Product }>());
export const deleteProduct = createAction('[Product API] Delete Product', props<{ id: number }>());
export const loadProducts = createAction('[Product API] Load Products');
                    
Creating Reducers

Create a reducer to handle product actions:


                        // src/app/state/product.reducer.ts
import { createReducer, on } from '@ngrx/store';
import { addProduct, editProduct, deleteProduct, loadProducts } from './product.actions';
import { AppState, Product } from './product.state';

export const initialState: AppState = {
    products: [],
};

export const productReducer = createReducer(
    initialState,
    on(addProduct, (state, { product }) => ({ ...state, products: [...state.products, product] })),
    on(editProduct, (state, { product }) => ({
        ...state,
        products: state.products.map(p => p.id === product.id ? product : p)
    })),
    on(deleteProduct, (state, { id }) => ({
        ...state,
        products: state.products.filter(product => product.id !== id)
    })),
    on(loadProducts, state => ({ ...state }))
);
                    
Registering the Store

Import the reducer in your main module:


                        // src/app/app.module.ts
import { StoreModule } from '@ngrx/store';
import { productReducer } from './state/product.reducer';

@NgModule({
    declarations: [/* your components */],
    imports: [
        StoreModule.forRoot({ products: productReducer }),
        // other imports
    ],
    providers: [],
    bootstrap: [/* your bootstrap component */]
})
                     
Using Store in a Component

Inject the store into your component and use it:


                        // src/app/product/product.component.ts
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { Product } from '../state/product.state';
import { addProduct, editProduct, deleteProduct, loadProducts } from '../state/product.actions';

@Component({
    selector: 'app-product',
    templateUrl: './product.component.html',
    styleUrls: ['./product.component.css'],
})
export class ProductComponent {
    products$: Observable = this.store.select(state => state.products);

    constructor(private store: Store) {
        this.loadProducts();
    }

    loadProducts() {
        this.store.dispatch(loadProducts());
    }

    addProduct() {
        const newProduct: Product = { id: Date.now(), name: 'New Product', price: 100 }; // Replace with real input
        this.store.dispatch(addProduct({ product: newProduct }));
    }

    editProduct(product: Product) {
        const updatedProduct = { ...product, price: product.price + 10 }; // Replace with real input
        this.store.dispatch(editProduct({ product: updatedProduct }));
    }

    deleteProduct(id: number) {
        this.store.dispatch(deleteProduct({ id }));
    }
}
                    
HTML Template

Example HTML to display, add, edit, and delete products:


                        <div>
<h1>Product List</h1>
<ul>
    <li *ngFor="let product of products$ | async">
        <span> - </span>
        <button (click)="editProduct(product)">Edit</button>
        <button (click)="deleteProduct(product.id)">Delete</button>
    </li>
</ul>
<button (click)="addProduct()">Add Product</button>
</div>
                    

This setup demonstrates a simple product management application using NgRx in Angular 19.

Receive the latest updates directly in your inbox!

Be the first to know about new updates and exclusive discounts. No spam, just great offers!

How about

A Custom Project?

With over 7 years of experienced team, we specialize in delivering custom projects for startups, blue-chip companies, and government agencies. We have successfully completed over 250+ projects, providing tailored solutions that meet the unique needs of each client.

Hire Us
Domiex Admin & Dashboards
230+

Total Pages

5+

Layouts

11+

Application

We provide quick support withing one business day to all of our customers.

© Domiex Created & Crafted by SRBThemes.