NgRx simple example

Creating a reducer example:

let’s say we have a file- account.reducer.ts

export function reducer(state, action) {
  switch (action.type) {

    case 'UPDATE_ACCOUNT_STATUS':
      return {
        ...state,
        accountStatus: action.payload
      };

    default:
      return state;
  }
}

Then in another file let’s say app.module.ts we import the reducer for root

import { StoreModule } from '@ngrx/store';
import { reducer } from './account.reducer';
 
@NgModule({
  imports: [
     StoreModule.forRoot(reducer)
  ], 
})
export class appModule { }

Then let’s make a templated page account.html:

<label>
<input type="text" value="" (change)="onChangeStatus($event.target.value)"/>
Account Status
</label>

<label>
{{ account.accountTemplateStatus}}

</label>

At last we update let’s say a file called account.component.ts with the action onChangeStatus (that will be triggered by a template page event).

When the event is triggered it dispatches an update to the store state causing any of the selector subscribers(“accounts” in this example) to be triggerd as well(updating the accountTemplateStatus property on the template):

import { Store,select } from '@ngrx/store';

constructor(private store: Store) { }
ngOnInit(): void {
      
    this.store.pipe(select('accounts')).subscribe(
      accounts => {
        if (accounts) {
          this.accountTemplateStatus = accounts.accountStatus;
        }
      });
  }
  onChangeStatus(value: int): void {
    this.store.dispatch({
      type: 'UPDATE_ACCOUNT_STATUS',
      payload: value
    });
  }


Comments are closed, but trackbacks and pingbacks are open.