I am implementing NGRX in my Angular 10 application and seem to have a problem with calling the reducer. I have created a checkbox in the app component. I am trying to maintain it's toggle state. I have created an action and reducer. I am not sure why the reducer is not getting called. I have written a console.log in the reducer which doesn't seem to fire. I haven't used strong typing of Action names but have ensured the names match.
app.module
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
StoreModule.forRoot(appReducer, {})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<input type="checkbox" id="checkMe" (change)="checkChanged()" [checked]="displayCode" />
<label for="checkMe">Check Me</label>
app.component
export class AppComponent implements OnInit {
title = 'Angular-NGRX-Practice';
displayCode: boolean;
constructor(private store: Store<any>) {
}
ngOnInit(): void {
this.store.select('app').subscribe(
app => {
if (app) {
this.displayCode = app.showCheck;
}
});
}
checkChanged(): void {
console.log('check changed fired!!!');
this.store.dispatch(
{ type: '[App] Toggle Check box' }
);
}
}
app.reducer
import { createAction, createReducer, on } from '@ngrx/store';
export const appReducer = createReducer({ showCheck: true },
on(createAction('[App] Toggle Check box'), state => {
console.log('Original State: showCheck', JSON.stringify(state));
return {
...state,
showCheck: !state.showCheck
};
})
);
I think you just need a slight change to app.module.ts
when registering the reducer
StoreModule.forRoot({ app: appReducer })