I am new to Angular 2. How to open a sidenav using mat component in Angular2. I am using this site but cannot resolve the issue. I have two different components Header, Sidebar. The toggle button is in Header component and sidenav is different component. I have tried using Event Emitter as well as services but cannot resolve the issue.enter image description here
1 Answers
i was facing the same problem .. i came up with the following sollution.
So i have a separate Navbar(nav-bar.component.ts)Component and a separate SideBar(sidebar.component.ts).
You were on the right path except i think the @HostBinding('class.open') is not a valid class for side nav. I came up with the below solution.
sidenav.component.ts
export class SideNavComponent implements OnDestroy{
isOpen: boolean;
ngOnInit(){
this._sideNavService.change.subscribe(isOpen =>{
console.log(isOpen)
this.isOpen = isOpen;
})
}
}
Below is the HTML for my side nav. NOTE : We can use property binding and bind to the "opened" property of the sidenav. I am using the variable isOpen to do that.
sidenav.component.html
<mat-sidenav-container class="example-sidenav-container" [style.marginTop.px]="mobileQuery.matches ? 56 : 0">
<mat-sidenav #sidenav [(opened)]="isOpen" [mode]="mobileQuery.matches ? 'over' : 'side'" [fixedInViewport]="mobileQuery.matches" fixedTopGap="56">
<mat-nav-list>
<a mat-list-item routerLink="." *ngFor="let nav of fillerNav">{{nav}}</a>
</mat-nav-list>
</mat-sidenav>
<div>Some Text<div>
</mat-sidenav-container>
Another thing to note is that I have placed a text in a div because apparently this implicitly creates a <mat-sidenav-content> tab without which the side nav wont be visible
I wrote a basic directive for the Navbar.
nav-bar.directive.ts
import { Component, HostListener, Directive, HostBinding, Input } from '@angular/core';
import { SideNavService } from "../_services/sideNav.service";
@Directive({ selector: '[sidebarButton]' })
export class HostDirective {
constructor(private sideNavService:SideNavService){}
@HostListener('click') onClick() {
console.log("Called")
this.sideNavService.toggle();
}
}
And a sideNav service for the two components to communicate.
sideNav.service.ts
import { Injectable, Output, EventEmitter} from "@angular/core";
@Injectable()
export class SideNavService{
isOpen = false;
@Output() change: EventEmitter <boolean> = new EventEmitter();
toggle(){
console.log("event fired")
this.isOpen = !this.isOpen;
this.change.emit(this.isOpen);
}
}
The above solution just fixes what the question mentions but is not an elegant solution