I have a parent component with the following template:
<app-sidebar></app-sidebar>
<router-outlet></router-outlet>
<app-footer></app-footer>
How can I show or hide the app-sidebar
or app-footer
component based on the component routing through the router outlet? I have a boolean showSidebar
I'd like to use, with it's value set to true or false on each child component.
<app-sidebar *ngIf=showSidebar></app-sidebar>
CodePudding user response:
Instead of direct component to component communication, you could use a service to share the show/hide flag and inject the service in the enclosing component as well as the the ones routed to.
For example child components' onInit, set a flag in the shared service instance. The parent component containing the router outlet, would read that flag and use it along with an *ngIf to show or hide parts of the template.
CodePudding user response:
In the app routes add a data property.
{ path: 'no-sidebar', component: NoSidebarComponent, canActivate: [AuthGuard], data: { showSidebar: false } },
and subscribe to the router events in the parent component like this
this.router.events.subscribe(event => {
if (event instanceof RoutesRecognized) {
const routeData = event.state.root.firstChild.data;
if (routeData) {
this.showSidebar = routeData.showSidebar === false ? false : true
}
}
}
CodePudding user response:
You can use subject variable, whenever you want to hide or show that time emits value of variable and subscribe to that variable in sidebar and footbar