noclist
noclist

Reputation: 1819

Angular show/hide on parent component based on child component

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>

Upvotes: 2

Views: 863

Answers (3)

Dhruvil Talaviya
Dhruvil Talaviya

Reputation: 49

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

Upvotes: 1

Mr. Stash
Mr. Stash

Reputation: 3160

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
      }
    }
  }

Upvotes: 1

Bahaa
Bahaa

Reputation: 1767

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.

Upvotes: 1

Related Questions