角度-侧边栏导航

时间:2020-05-12 03:06:18

标签: css angular typescript angular-bootstrap

我不是在折叠时使用常规的引导幻灯片向下导航,而是尝试从左侧导航创建幻灯片。

切换按钮的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 Link

1 个答案:

答案 0 :(得分:1)

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

styles.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() {
  }

}

当然,可以对上面的代码进行额外的增强,但是我希望它向您展示了您尝试实现的方法。