How do you connect NgRx Store to an application?
To connect NgRx Store to an Angular application, you need to go through a few simple steps:
1. Install NgRx
In the terminal:
bash
npm install @ngrx/store(later you can add other parts too: @ngrx/effects, @ngrx/store-devtools, @ngrx/entity, etc.)
2. Create the initial state and reducer
Example: counter.reducer.ts
ts
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
export const counterReducer = createReducer(
initialState,
on(increment, state => state + 1),
on(decrement, state => state - 1),
on(reset, _ => 0)
);3. Create actions
Example: counter.actions.ts
ts
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const reset = createAction('[Counter] Reset');4. Add Store to AppModule
ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
@NgModule({
imports: [
BrowserModule,
StoreModule.forRoot({ count: counterReducer }) // connect the reducer
],
bootstrap: [/* your root component */]
})
export class AppModule {}5. Use Store in the component
ts
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
@Component({
selector: 'app-counter',
template: `
<button (click)="decrement()">-</button>
{{ count$ | async }}
<button (click)="increment()">+</button>
<button (click)="reset()">Reset</button>
`
})
export class CounterComponent {
count$ = this.store.select(state => state.count); // get the value
constructor(private store: Store<{ count: number }>) {}
increment() {
this.store.dispatch(increment());
}
decrement() {
this.store.dispatch(decrement());
}
reset() {
this.store.dispatch(reset());
}
}Conclusion:
You connect StoreModule in AppModule, create actions and a reducer, and use store.select() and store.dispatch() in components.
NgRx starts tracking the state and automatically updates the template on changes.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.