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
});
Author by
Joseph
Updated on June 12, 2022Comments
-
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>
-
Vega almost 7 yearsDo the two components have a common parent component?
-
Joseph almost 7 years@Vega. Yes. they are under the core.component.html. Pls see updated image
-
Vega almost 7 yearsThe both have core component as parent? The structure doesn't tell about it
-
Joseph almost 7 yearsYes. Did you see the image?
-
Vega almost 7 yearsYes the image doesn't tell how they are related. Post core.html please
-
Joseph almost 7 years@Vega. Please check again. I've added it
-
-
Joseph almost 7 years@IIyaSurmay. Can you do it using my code above. Thanks
-
IlyaSurmay almost 7 yearsYou haven't provided the code of your class, just html. Paste it here.
-
Joseph almost 7 yearsI didn't put anything in typescript yet
-
Mayur Kukadiya about 5 yearsIn sidebar, where this subscribe code should I put ?