Welcome to this comprehensive tutorial on NgRx Component Store! In this lesson, we'll delve into the world of state management in Angular applications using NgRx, a powerful library for managing state in Angular applications. By the end of this tutorial, you'll be able to implement NgRx Component Store in your own projects. 🎯
NgRx is an Angular-specific package for Redux, a predictable state container and side-effects library. It provides a powerful solution for managing application state in a predictable and testable manner, making it ideal for large-scale Angular applications. 📝
First, let's install NgRx in our Angular project:
npm install @ngrx/store @ngrx/effects --save
Now, let's create our first NgRx store!
store folder in the app directory.store folder, create a new file named app.store.module.ts.import { StoreModule } from '@ngrx/store';
import { appReducer } from './reducers';
@NgModule({
imports: [StoreModule.forRoot({ app: appReducer })],
})
export class AppStoreModule { }store folder, create a new file named reducers and inside it, create a new file named index.ts.import { createReducer, on } from '@ngrx/store';
import * as CounterActions from './counter.actions';
export const initialState = { counter: 0 };
export const counterReducer = createReducer(
initialState,
on(CounterActions.increment, state => ({ counter: state.counter + 1 })),
on(CounterActions.decrement, state => ({ counter: state.counter - 1 })),
);counter.actions.ts inside the reducers folder.export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');AppStoreModule to the AppModule imports.import { AppStoreModule } from './store/app.store.module';
@NgModule({
imports: [AppStoreModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule { }Now, let's inject and connect our store to our component!
StoreModule and our action types in the component.import { Store, select } from '@ngrx/store';
import { CounterActions } from '../store/reducers/counter.actions';Store in the constructor.constructor(private store: Store) {}select operator to access the state and dispatch actions.this.counter$ = this.store.pipe(
select(state => state.counter),
);
incrementCounter() {
this.store.dispatch(CounterActions.increment);
}
decrementCounter() {
this.store.dispatch(CounterActions.decrement);
}Now, you have a basic understanding of how to create and use an NgRx store in an Angular application!
Which Angular library is NgRx based on?
In the next sections, we'll dive deeper into NgRx concepts, including selectors, effects, and more! 🚀
Stay tuned for more on NgRx Component Store! 💡