Sidenav Select
To recap, we have:
- Declared two actions:
HideSidenavandShowSidenav. - Declared a
reducer()function to mutate the state of our application based on the actions dispatched. - Declared the
sidenavfeature state. - Declared the
sidenavStatefeature selector and thesidenavIsOpenselector functions.
With our actions, reducer and selectors declared we are ready to implement the behavior in our Angular application.
Shell Component
The Angular application in src/app uses a ShellComponent along with a RouteService class to wrap our application using Angular Material.
The RouteService class is located at src/app/core/services/route.service.ts:
export class RouteService {
static withShell(routes: Routes): Route {
return {
path: '',
component: ShellComponent,
children: routes,
data: { reuse: true }
};
}
}The withShell() static method returns a new Route object with the ShellComponent as the parent component of the provided routes.
Inject Store
First, we need to use dependency injection to access the Store singleton object.
Open src/app/core/shell/shell.component.ts and update the constructor() function to accept the Store:
import { Store } from '@ngrx/store';
import { State } from '@app/state';
export class ShellComponent {
constructor(private store: Store<State>) {}
}Define opened Property
Next, define a new opened property:
export class ShellComponent {
opened: Observable<boolean>;
constructor(private store: Store<State>) {}
}The opened property is an Observable whose notifications are boolean values: true if the sidenav is opened and false if the sidenav is closed.
Declare opened
Now, declare the value of the opened property using the State object.
export class ShellComponent implments OnInit {
opened: Observable<boolean>;
constructor(private store: Store<State>) {}
ngOnInit() {
this.opened = this.store.pipe(select(sidenavIsOpen));
}
}- The
Storesingleton object is both anObserverand anObservable. - Since it is an
Observablewe can invoke thepipe()method. - We use the
select()operator from the @ngrx/store module to select a slice of data within the state object. - We specify the
sidenavIsOpenselector we declared previously.
Review ShellComponent Template
Let's quickly review part of the shell.component.html template:
<mat-sidenav
#sidenav
[mode]="isMobile ? 'over' : 'side'"
[opened]="opened | async"
>
<!-- code omitted -->
</mat-sidenav>- The
openedinput for the<mat-sidenav>component is bound to theopenedproperty we declared in theShellComponentclass. - Note the use of the
AsyncPipethat subscribes (and unsubscribes) to theopenedobservable.