Joseph
Joseph

Reputation: 7755

Toggle SideBar Menu from other component in Angular 4

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

Upvotes: 2

Views: 13197

Answers (1)

IlyaSurmay
IlyaSurmay

Reputation: 2333

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

Upvotes: 6

Related Questions