angular 2 - how to hide nav bar in some components
Navbar control and formatting is often needed throughout an app, so a NavbarService is useful. Inject in those components where you need.
navbar.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class NavbarService {
visible: boolean;
constructor() { this.visible = false; }
hide() { this.visible = false; }
show() { this.visible = true; }
toggle() { this.visible = !this.visible; }
doSomethingElseUseful() { }
...
}
navbar.component.ts:
import { Component } from '@angular/core';
import { NavbarService } from './navbar.service';
@Component({
moduleId: module.id,
selector: 'sd-navbar',
templateUrl: 'navbar.component.html'
})
export class NavbarComponent {
constructor( public nav: NavbarService ) {}
}
navbar.component.html:
<nav *ngIf="nav.visible">
...
</nav>
example.component.ts:
import { Component, OnInit } from '@angular/core';
import { NavbarService } from './navbar.service';
@Component({
})
export class ExampleComponent implements OnInit {
constructor( public nav: NavbarService ) {}
}
ngOnInit() {
this.nav.show();
this.nav.doSomethingElseUseful();
}
I was able to solve this without using a nav/toolbar service by adding a data object to the route in the route.module. I expanded on Todd Motto's example of adding dynamic titles to a page and added toolbar: false/true
to the data object in my path. I then subscribed to the router events in my toolbar.component. Using Todd's event listener func, I read the path object and used the boolean value to set the toolbar visible or not visible.
No service needed and works on pagerefresh.
routing module
...
const routes: Routes = [
{ path: 'welcome', component: WelcomeComponent, data: { title: 'welcome', toolbar: false} }, ...];
toolbar.component
constructor(private router: Router, private activatedRoute: ActivatedRoute, public incallSvc: IncallService) {
this.visible = false; // set toolbar visible to false
}
ngOnInit() {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
)
.pipe(
filter(route => route.outlet === 'primary'),
mergeMap(route => route.data),
)
.subscribe(event => {
this.viewedPage = event.title; // title of page
this.showToolbar(event.toolbar); // show the toolbar?
});
}
showToolbar(event) {
if (event === false) {
this.visible = false;
} else if (event === true) {
this.visible = true;
} else {
this.visible = this.visible;
}
}
toolbar.html
<mat-toolbar color="primary" *ngIf="visible">
<mat-toolbar-row>
<span>{{viewedPage | titlecase}}</span>
</mat-toolbar-row>
</mat-toolbar>