I want to toggle side-nav(in the drawer component)by clicking menu icon (in the header component). I've tried using service; but the service state didn't share between these two components.
The demo is here https://stackblitz.com/edit/angular-11pdkj
I want to toggle side-nav(in the drawer component)by clicking menu icon (in the header component). I've tried using service; but the service state didn't share between these two components.
The demo is here https://stackblitz.com/edit/angular-11pdkj
You should use the @Input and @Output decorators and the EventEmitter to send event from one to another component.
I've fixed your code,
Please check it out:
stackblitz
Angular provides very powerful concept of Input, Output.
Please consider to use Input, Output and EventEmitter
with this all you can bounce event from one component to another component.
Please have a look on this demo link.
// drawer.component.ts
export class DrawerComponent implements AfterViewInit, OnChanges {
@ViewChild('sidenav') public sidenav: MatSidenav;
@Input()
openNav: boolean;
ngOnChanges(): void {
console.log('ngOnChanges', this.openNav);
if (this.openNav) {
this.sidenav.open();
} else {
this.sidenav.close();
}
}
}
// header.component.ts
export class HeaderComponent implements OnInit {
title: string = "Dashboard";
@Output()
open: EventEmitter<boolean> = new EventEmitter();
clickMenu() {
this.open.emit(true);
}
}
// layouts.component.html
<div class="app-wrapper">
<app-drawer [openNav]="isOpen"></app-drawer>
<app-header (open)="navOpen($event)"></app-header>
<div>
// layouts.component.ts
export class LayoutsComponent implements OnInit {
isOpen: boolean;
navOpen($event): void {
this.isOpen = !this.isOpen;
console.log('navOpen', $event);
}
}
also use respective component lifecycle hooks whenever required.
I solved this problem by not setting the sidenav in the service but turning the service into a notifier when the sidenav needs to toggle. So when you click the button the service tells a behaviour subject to emit it's change to the DrawerComponent. This component subscribes to the behaviour subject in the ngOnInit. And toggles the sidenav when the service notifies the component of the toggle.
The following StackBlitz shows how I fixed your code: https://stackblitz.com/edit/angular-mgm4xn