Open/Close sidenav from another component

I had the same problem using. I resolved it like this.

SidenavService

import { Injectable } from '@angular/core';
import { MatSidenav } from '@angular/material';

@Injectable()
export class SidenavService {
    private sidenav: MatSidenav;


    public setSidenav(sidenav: MatSidenav) {
        this.sidenav = sidenav;
    }

    public open() {
        return this.sidenav.open();
    }


    public close() {
        return this.sidenav.close();
    }

    public toggle(): void {
    this.sidenav.toggle();
   }

Your Component

constructor(
private sidenav: SidenavService) { }

toggleRightSidenav() {
   this.sidenav.toggle();
}

Bind your html toggle() based on your requirement.

App component.

@ViewChild('sidenav') public sidenav: MatSidenav;

constructor(private sidenavService: SidenavService) {
}

ngAfterViewInit(): void {
  this.sidenavService.setSidenav(this.sidenav);
}

App Module

providers: [YourServices , SidenavService],

Working sample with code stackblitz

Angular 9+ Update

Per this answer on SO, “Components can no longer be imported through @angular/material. Use the individual secondary entry-points, such as @angular/material/button.” As such, make sure to import MatSidenav like so:

import { MatSidenav } from '@angular/material/sidenav';

Leave a Comment