Skip to main content

Angular NgRx: The Most Simplest Store


Greetings!

When learning Angular, one of the difficulties we face (including myself) is understanding NgRx. In theory, it is so simple. However, difficulty is in implementation. I don't want to add lengthy explanations (documentation has better explanation anyway) but want to add simplest working examples incrementatly so that anyone in any level can understand.
Let's create the most simplest store then :). A simple value stored in the store!!!

What we need

  • Store with initial value
  • A reducer
  • A component to read the value
Yes, no action, no effects as this example is so simple.

Generate the Project

ng new ngrx-hello-store --routing=false --style=css
cd ngrx-hello-store/
ng add @ngrx/store@latest
ng serve

Initiate the Reducer

We will store a simple message in our store.
ngrx-hello-store/src/app/hello.reducer.ts
import { Action, createReducer } from '@ngrx/store';

const initialState: string = 'Hello Store';
 
export const messageReducer = createReducer(
  initialState
);

Register the Reducer

We register our register with the name 'message'.
ngrx-hello-store/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { messageReducer } from './hello.reducer';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    StoreModule.forRoot({
      message: messageReducer
    }, {})
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
That is it!!! we have setup our most simplest store. Now we can listen this initial value in our component.

Reading the Value

ngrx-hello-store/src/app/app.component.ts
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  helloObserver$: Observable<string>;

  constructor(private helloStore: Store<{ message: string }>) {
    this.helloObserver$ = helloStore.select('message');
  }

}
Store comes with different 'select' variations, we are using simple string selector here. Note that this 'message' is the name we provided in StoreModule when registering the reducer.

Now we can add this value into our template.

ngrx-hello-store/src/app/app.component.html
{{ helloObserver$ | async }}
Note that async pipe will automatically subscribe and unsubscribe to our Observable.

If you are wondering about best practices, no.. this is not about best practices. This is to provide very basic working example :).

If you have come so far, congratulations on your first ngrx store. If you already know this much, don't worry we are going to work with actions in our next article.

Happy coding ;)