首页 > 解决方案 > Angular - 侧边栏导航

问题描述

我试图从左侧导航中创建一个幻灯片,而不是传统的引导程序在折叠时向下滑动导航。

切换按钮的 HTML

<button id="collapseBtn" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" (click)="toggleSideBar()" >
Toggle</button>

侧边栏的 HTML

<div class="sidebar">
  <ul>
      <li>S-Dashboard</li>
      <li>S-Voucher</li>
  </ul>
</div>

侧边栏的 CSS

.sidebar {
   background: #1a2580;
   color: white;
   height: 100%;
   width: 0;
   position: fixed; 
   z-index: 1;
   top: 0;
   left: 0;
   overflow-x: hidden;
   padding-top: 60px;
   transition: 0.5s; 
}
.showsidebar {
   width: 250px;
}
.hidesidebar {
   width: 0px;
}

组件文件中的 ToggleSideBar 函数

toggleSideBar() {
   document.getElementsByClassName('sidebar')[0].classList.add('showsidebar');
   this.sideBarOpen = true;
}

单击切换按钮会根据需要滑出导航,但不会将内容推到右侧。结果,内容隐藏在侧边栏下方。

如何将内容向右推送?

其次,我尝试在单击页面上的任何位置时使用 HostListener 关闭侧边栏,但这似乎不起作用。

StackBlitz 链接

标签: cssangulartypescriptangular-bootstrap

解决方案


body当您切换侧边菜单时,您可以切换应该负责移动(推送)整个页面内容的元素上的类。

样式.css

body { 
  position: relative;
  overflow: hidden;
  transition: left 0.5s ease; /* Animation styles are just for demo */
  left:0;
}

body.push {
  left:250px;
}

并在您的组件中:

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


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

  isMenuSmall:boolean = true;
  sideBarOpen: boolean = false;
  constructor(private el:ElementRef) { }

 // Your initial click listener on the host element
 @HostListener('click', ['$event'])onClick(event) {
      event.stopPropagation();
   if (event.target.id == "collapseBtn") {
      document.getElementsByClassName('sidebar')[0].classList.add('showsidebar');
      document.body.classList.add('push');
      this.sideBarOpen = true;
   } else {
    if (this.sideBarOpen) {
       document.getElementsByClassName('sidebar')[0].classList.remove('showsidebar');
       document.body.classList.remove('push');
       this.sideBarOpen = false;
    }
   }
 }

  // Click listener on the window object to handle clicks anywhere on 
  // the screen.
  @HostListener('window:click', ['$event']) onOutsideClick(event){
    if(this.sideBarOpen && !this.el.nativeElement.contains(event.target)){
      this.sideBarOpen=false;
      document.getElementsByClassName('sidebar')[0].classList.remove('showsidebar');
      document.body.classList.remove('push');
    }
  }

  ngOnInit() {
  }
  toggleSideBar() {
  }

}

当然,上面的代码可以额外增强,但我希望它向您展示了您想要实现的目标的方法。


推荐阅读