Toggle SideBar Menu from other component in Angular 4

12,382

You can use shared service to open sidebar. Create a service vith EventEmitter and emit an event when you want to open a sidebar. Then, in sidebar component, subscribe to that EventEmitter and open/close sidebar every time when event is fired.

For example:

Service

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class CoreService {
  public toggleSidebar: EventEmitter<any> = new EventEmitter();
}

Header

public openSidebar() {
  this.coreService.toggleSidebar.emit();
}

Sidebar

this.coreService.toggleSidebar.subscribe(() => {
  //open your sidebar by setting classes, whatever
});
Share:
12,382
Joseph
Author by

Joseph

Updated on June 12, 2022

Comments

  • Joseph
    Joseph about 2 years

    How can i implement sidebar toggle menu in my angular app. I'm confused on how to call the sidebar menu in the other component. My toggle button is found on the header component. It's purpose is show the sidebar menu when i click the toggle button on the header component.

    header.component.html

      <div class="navbar-header"><a id="toggle-btn" href="#" class="menu-btn"><i class="icon-bars"> </i></a><a href="index.html" class="navbar-brand">
                  <div class="brand-text"><span>MCDONALDS</span></div></a></div>
    

    sidebar.component.html

    <nav class="side">
      <h1>CLICK TO Show Me</h1>
      </nav>
    

    core.component.html

    <app-header></app-header>
    <app-sidebar></app-sidebar>
    

    enter image description here

    • Vega
      Vega almost 7 years
      Do the two components have a common parent component?
    • Joseph
      Joseph almost 7 years
      @Vega. Yes. they are under the core.component.html. Pls see updated image
    • Vega
      Vega almost 7 years
      The both have core component as parent? The structure doesn't tell about it
    • Joseph
      Joseph almost 7 years
      Yes. Did you see the image?
    • Vega
      Vega almost 7 years
      Yes the image doesn't tell how they are related. Post core.html please
    • Joseph
      Joseph almost 7 years
      @Vega. Please check again. I've added it
  • Joseph
    Joseph almost 7 years
    @IIyaSurmay. Can you do it using my code above. Thanks
  • IlyaSurmay
    IlyaSurmay almost 7 years
    You haven't provided the code of your class, just html. Paste it here.
  • Joseph
    Joseph almost 7 years
    I didn't put anything in typescript yet
  • Mayur Kukadiya
    Mayur Kukadiya about 5 years
    In sidebar, where this subscribe code should I put ?