Struggling to hide a sidebar menu after clicking on a menu item that you created? I ran into the same issue and tried following the example from a tutorial on
Do I really need to call toggleMenu on (click) of every hyperlink in the HTML? If so, how do I invoke a method that resides in app.component.ts from another component?
Help needed...
Currently, I'm working with Angular 4 and bootstrap 4.
Check out the relevant code snippets below:
<button (click)="toggleMenu()" class="hamburger">
<span>toggle menu</span>
</button>
<navigation-component [@slideInOut]="menuState"> </navigation-component>
<div class="container-fluid">
<alert></alert>
<router-outlet></router-outlet>
</div>
app.component.ts:
@Component({
selector: 'app-root',
templateUrl: './' + (window.innerWidth > 745 ?
'app.component.html' :
'app.component.mobile.html'),
styleUrls: ['./app.component.css'],
animations: [
trigger('slideInOut', [
state('in', style({
transform: 'translate3d(0, 0, 0)'
})),
state('out', style({
transform: 'translate3d(100%, 0, 0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
]),
]
})
toggleMenu() {
// Toggle the menu state
this.menuState = this.menuState === 'out' ? 'in' : 'out';
}
Need more guidance? Check out the links below for further reference:
https://stackblitz.com/edit/dynamic-nested-sidenav-menu
Here's the updated code snippet for navigation.component.ts:
toggleMenu() {
this.toggleMenu();
}
Stay on track with this solution:
After incorporating the code suggested by Santosh in app.component.ts, everything worked smoothly. Big thanks to Santosh!
constructor(private http: Http,
private router: Router,
public zone: NgZone) {
router.events.subscribe( (event: Event) => {
if (event instanceof NavigationStart) {
this.menuState = 'out';
}
if (event instanceof NavigationEnd) {
// Hide loading indicator
}
if (event instanceof NavigationError) {
// Hide loading indicator
// Present error to user
console.log(event.error);
}
});
}