簡體   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