Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if material2 sidenav is open

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();
     }
  }

}
like image 254
Runtime Terror Avatar asked Jan 11 '17 12:01

Runtime Terror


People also ask

How do I know if my Sidenav mat is open?

From the docs: A mat-sidenav can be opened or closed using the open(), close() and toggle() methods. Each of these methods returns a Promise that will be resolved with true when the sidenav finishes opening or false when it finishes closing.

How do you toggle Sidenav?

Opening and closing a sidenav A <mat-sidenav> can be opened or closed using the open() , close() and toggle() methods.

How do I use Sidenav in angular materials?

The <mat-sidenav>, an Angular Directive, is used to create a side navigation bar and main content panel with material design styling and animation capabilities. <mat-sidenav-container> - Represents the main container. <mat-sidenav-content> - Represents the content panel. <mat-sidenav> - Represents the side panel.

What is MatDrawer?

MatDrawer. This component corresponds to a drawer that can be opened on the drawer container.


2 Answers

You have to use ViewChild to get control over sidenav

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

Plunkr

like image 179
Pankaj Parkar Avatar answered Oct 04 '22 00:10

Pankaj Parkar


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}`);
}
like image 39
Phyrum Tea Avatar answered Oct 04 '22 01:10

Phyrum Tea