繁体   English   中英

如何在angular 2材质中隐藏侧面导航栏

[英]How to hide side navigation bar in angular 2 material

我正在尝试使用 angular 2 材料创建响应式侧边导航栏。 我的侧面导航正在工作。 它总是打开导航栏。如何在缩小屏幕尺寸时隐藏它。

这是我的代码:

<md-sidenav-container style="width: 100%" onloadstart="false">
  <div class="flex-container" fxLayout="row" fxLayout.xs="column" fxLayoutAlign="center center" fxLayoutAlign.xs="start">
    <md-toolbar color="primary">
      <md-icon>menu</md-icon>
      <span>Profile</span>
      <span class="example-fill-remaining-space"></span>
      <span>
        <button md-icon-button [mdMenuTriggerFor]="menu"><md-icon>more_vert</md-icon></button>
        <md-menu #menu="mdMenu">
          <button md-menu-item><md-icon>swap_horiz</md-icon><span>toggle</span></button>
          <button md-menu-item disabled><md-icon>person</md-icon><span>profile</span></button>
          <button md-menu-item><md-icon>exit_to_app</md-icon><span>log out</span></button>
        </md-menu>
      </span>
    </md-toolbar>
    <md-sidenav-layout class="demo-sidenav-layout">
      <md-sidenav align="start" mode="side" opened>
        <md-list>
          <md-list-item>
            <a routerLink="profile-home"><button md-button ><md-icon>home</md-icon> Home </button></a></md-list-item>
          <md-list-item>
            <a routerLink="profile-security"><button md-button ><md-icon>security</md-icon> Security </button></a></md-list-item>
          <md-list-item>
            <a routerLink="profile-settings"><button md-button ><md-icon>settings</md-icon>Settings </button></a></md-list-item>
        </md-list>
      </md-sidenav>
      <router-outlet></router-outlet>
    </md-sidenav-layout>
  </div>
</md-sidenav-container> 

只需在您的md-sidenav中添加一个类,然后在屏幕足够小时将该类隐藏即可。

在您的模板中,将该类添加到md-sidenav

...

<md-sidenav align="start" mode="side" opened class="hide-on-small-screens">
        <md-list>
          <md-list-item>

...

在您的CSS中,实现您的类

...

@media only screen and (max-width: 500px) {
    .hide-on-small-screens {
        display: none;
    }
}

...

如果屏幕小于或等于500像素,这将隐藏sidenav。 查找媒体查询以获取有关如何使用此方法的更多信息。

我知道样式应该保留在CSS中,但是我采用了另一种方法来解决此问题。

我利用Angular ViewChild和Hostlistener模块以编程方式进行控制。 当窗口大小更改时,它使您可以更好地控制要执行的操作。

在您的视图/ html中:

<md-sidenav #sidenav align="start" mode="side" opened>
    ...
</md-sidenav/>

在您的打字稿文件中:

import { ViewChild, HostListener } from '@angular/core';
import { MdSidenav } from '@angular/material';

export class ClassName implements AfterViewInit {
    @ViewChild('sidenav') sidenav: MdSidenav;

    constructor() {}

    @HostListener('window:resize', [$event])
    onResize(event): void {
        if (this.sidenav !== undefined) {
            if (event.target.innerWidth <= 500) { // This can be any value.
                this.sidenav.close();
            } else {
                this.sidenav.open();
            }
        }
    }
}

使用这种方法,onResize方法将在每次执行窗口调整大小事件时运行。

您的视图文件:您必须在组件html文件中添加#sidenav文档引用变量。

<mat-sidenav #sidenav>
   ...
 </mat-sidenav>

您的TS文件:您在html文件中声明的变量可以使用@viewchild帮助在ts组件文件中访问该变量,请不要忘记为MatSidenav定义sidenav的类型。 之后,您可以轻松访问MatSidenav上所有可用的方法,例如关闭,打开,切换等。

 import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatSidenav } from '@angular/material';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {

      @ViewChild('sidenav') sidenav: MatSidenav;
      constructor(){

      }

      ngOnInit(){}

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

看来Angular库中有MediaQueryList。 它可以收听媒体屏幕更改,并以用户定义的样式对其进行响应。

来源: 为移动设备和桌面创建一个响应方导航布局

示例: https//stackblitz.com/angular/ebabmjapakm?file = app%2Fsidenav-sensitive-example.ts

* .component.ts

import {MediaMatcher} from '@angular/cdk/layout';
import {ChangeDetectorRef, Component, OnDestroy} from '@angular/core';

/** @title Responsive sidenav */
@Component({
  selector: 'sidenav-responsive-example',
  templateUrl: 'sidenav-responsive-example.html',
  styleUrls: ['sidenav-responsive-example.css'],
})
export class SidenavResponsiveExample implements OnDestroy {
  mobileQuery: MediaQueryList;

  fillerNav = Array.from({length: 50}, (_, i) => `Nav Item ${i + 1}`);

  fillerContent = Array.from({length: 50}, () =>
      `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
       labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
       laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
       voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
       cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`);

  private _mobileQueryListener: () => void;

  constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher) {
    this.mobileQuery = media.matchMedia('(max-width: 600px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

  ngOnDestroy(): void {
    this.mobileQuery.removeListener(this._mobileQueryListener);
  }
}


/**  Copyright 2019 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */

* .component.html

<div class="example-container" [class.example-is-mobile]="mobileQuery.matches" *ngIf="shouldRun">
  <mat-toolbar color="primary" class="example-toolbar">
    <button mat-icon-button (click)="snav.toggle()"><mat-icon>menu</mat-icon></button>
    <h1 class="example-app-name">Responsive App</h1>
  </mat-toolbar>

  <mat-sidenav-container class="example-sidenav-container"
                         [style.marginTop.px]="mobileQuery.matches ? 56 : 0">
    <mat-sidenav #snav [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>

    <mat-sidenav-content>
      <p *ngFor="let content of fillerContent">{{content}}</p>
    </mat-sidenav-content>
  </mat-sidenav-container>
</div>

* .component.css

.example-container {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.example-is-mobile .example-toolbar {
  position: fixed;
  /* Make sure the toolbar will stay on top of the content as it scrolls past. */
  z-index: 2;
}

h1.example-app-name {
  margin-left: 8px;
}

.example-sidenav-container {
  /* When the sidenav is not fixed, stretch the sidenav container to fill the available space. This
     causes `<mat-sidenav-content>` to act as our scrolling element for desktop layouts. */
  flex: 1;
}

.example-is-mobile .example-sidenav-container {
  /* When the sidenav is fixed, don't constrain the height of the sidenav container. This allows the
     `<body>` to be our scrolling element for mobile layouts. */
  flex: 1 0 auto;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM