Mohag519
Mohag519

Reputation: 426

Angular component does not reflect NGRX store state

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.

Upvotes: 0

Views: 656

Answers (1)

enno.void
enno.void

Reputation: 6579

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

select(x => x.appStore.showSideNav)

Upvotes: 1

Related Questions