Angular 2 Material SideNav always open on desktp and normal on mobile

后端 未结 3 2110
面向向阳花
面向向阳花 2021-01-17 04:53

I made this simple side nav in angular 2 material. I want to keep oppened=\"true\" only for desktop and keep the default behavior for mobiles and laptops. This used to be pr

3条回答
  •  青春惊慌失措
    2021-01-17 05:40

    After struggling myself a bit for this similar post, I used what seems like a bit of a hack that I found at https://github.com/angular/material2/issues/1130, and which I've put in this plunker.

    The key in this solution is that it checks the media size on open, and on resize event, showing/hiding the side navigation panel depending on width available. Credit for this goes to sikemullivan

    ngOnInit() {
        window.onresize = (e) => {
          this.checkMenu();
        };
        this.checkMenu();
      }
    
      checkMenu() {
        this._ngZone.run(() => {
          var w = window.innerWidth;
          if (w > 450) {
            this.start.open();
          } else {
            this.start.close();
          }
        });
      }
    

    I call it a hack, because handling this through a resize event handler seems like taking out a sledge hammer to solve the problem. I would think there's something easier, but couldn't find anything easier myself.

    Another issue with the above, is that if you're like me, maybe you'd like something that keeps open, then you'd need an answer to Prevent md-sidenav from being closed using Escape key when opened

提交回复
热议问题