0
votes

I am playing around with Angular and ngrx and have followed several different tutorials to get some ngrx-store started. I'm using ngrx-10 and angular-11. The setup is rather minimal.

app/store/action.ts

export const toggleSideNav = createAction('[SideNav Component] Toggle', props<{showSideNav?: boolean}>());

app/store/reducer.ts

export interface AppState {
    showSideNav: boolean
}

export const initialState: AppState = {
    showSideNav: true
};

const _appReducer = createReducer(
    initialState,
    on(toggleSideNav, (state: AppState, {showSideNav}) => ({...state, showSideNav: showSideNav ?? !state.showSideNav }))
);

export function AppReducer(state: AppState = initialState, action: Action) {
    return _appReducer(state, action);
}

app.module.ts

...
StoreModule.forRoot({appStore : AppReducer}, {})
...

/visitors(submodule)/components/home.component.ts

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {

  showSideNav$: Observable<boolean>;

  constructor(private store: Store<AppState>) { 
    this.showSideNav$ = store.pipe(select(x => x.showSideNav))
  }

  ngOnInit(): void {
  }

  toggleSideNav(): void {
    this.store.dispatch(toggleSideNav({}));
  }
}

And finally, /visitors/components/home.component.html

<div *ngIf="showSideNav$ | async">
    it works
</div>
<button (click)="toggleSideNav()">
    Toggle
</button>

I am using ngrx-devtools and I can see the toggling of the "showSideNav" works. It flops between true and false but the text never shows. It's as if showSideNav$ is always undefined.

1
I realise this isn't helpful and will not go towards answering your question at all, but my own question I have is why you are making use of ngrx store? Bit of a personal quest of mine to find out why people are using it as I've so far seen no benefits to using it. It has only sewn misery and despair throughout every project I've seen attempt to use it.Krenom
It's interesting you ask that. I have read an article discussing exactly this and I did start to think about leaving ngrx. But as I said in the post, I'm playing around to learn Angular and the things around it. I have earlier used React+Redux(MobX) professionally and that worked well for me so I like the "store-concept". Maybe in the end what I learn from this laborating is to stay away from ngrx, which is fine. I just cant abandon it before I solving this issue.Mohag519
ngrx is great for big applications (good schematics, good structure, convenient way to select from the store). For small applications it may have too much boilerplateenno.void

1 Answers

1
votes

Your selector returns undefined. I guess your selector function should look like this:

select(x => x.appStore.showSideNav)