6

Is there a way to check if the sidenav element is open? According the API documentation, there is a isOpen? parameter, but in my case it throws an exception: EXCEPTION: Error in ./AppComponent class AppComponent - inline template:2:2 caused by: this.sidenav.isOpen is not a function

import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-sidebar',
  template: `
  <md-sidenav #sidenav mode="side" class="app-sidenav">
      Sidenav
  </md-sidenav>
  `,
  styleUrls: ['./sidebar.component.css'],
  host: {
      '(document:click)': 'onClick($event)',
  }
})
export class SidebarComponent implements OnInit {

  constructor(private sidenav: ElementRef) { }

  ngOnInit() {
  }

  onClick() {
     if (this.sidenav.isOpen()) {
         this.sidenav.close();
     }
  }

}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Runtime Terror
  • 6,242
  • 11
  • 50
  • 90

2 Answers2

14

You have to use ViewChild to get control over sidenav

@ViewChild('sidenav') sidenav: any;
opened: any = false;
onClick() {
   console.log(this.sidenav.opened);
}

Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
4

You misunderstand the documentation, isOpen? is an optional parameter of the toggle function.

You can check it's property instead. This works for me:

@ViewChild('sidenav') sidenav: MatSidenav;
onClick() {
  console.log(`isOpen: ${this.sidenav.opened}`);
}
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Phyrum Tea
  • 2,623
  • 1
  • 19
  • 20