首页 > 解决方案 > Angular:如果用户单击屏幕上的任何位置,则关闭 sidenav

问题描述

我正在为我的 sidenav 使用库并遇到问题。如果用户单击屏幕上的任何位置,我必须关闭 sidenav。我尝试了几件事,但没有什么对我有用。

这是代码:

html

 <ul class="navdrawer-nav">
  <li class="nav-item">
    <a class="nav-link" (click) = "hideNavbar()" [routerLinkActive]="['active']" *ngIf="[1, 2, 3,5].indexOf(userRoleValue) > -1"
       [routerLinkActiveOptions]="{ exact: true }" [routerLink]="['/dashboard']">
       <svg class="mr-3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"/><path d="M21 20a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9.49a1 1 0 0 1 .386-.79l8-6.222a1 1 0 0 1 1.228 0l8 6.222a1 1 0 0 1 .386.79V20zm-2-1V9.978l-7-5.444-7 5.444V19h14z" fill="rgba(0,150,136,1)"/></svg>
        Dashboard</a>
  </li>
  ......
  ......
<main class="container-fluid" id="dView" (click) = "hideNavbar()"> //here I am trying to close the sidenav if the user clicks anywhere on the screen
  <router-outlet></router-outlet>
</main>

ts

hideNavbar()
{
  $('#navdrawerDefault').removeClass('show');
}

但是,它不起作用。当我单击屏幕上的任意位置时,sidenav 不会关闭。任何帮助,将不胜感激。谢谢!

标签: angular

解决方案


用于处理元素外的点击事件的 Angular 指令。对于在下拉菜单或模态对话框之外点击做出反应的事情很有用。

第1步

     `npm install --save ng-click-outside`

设置 2

import { ClickOutsideModule } from 'ng-click-outside';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ClickOutsideModule],
  bootstrap: [AppComponent]
})
class AppModule {}

步骤 3

@Component({
  selector: 'app',
  template: `
    <div (clickOutside)="onClickedOutside($event)">Click outside this</div>
  `
})
export class AppComponent {
  onClickedOutside(e: Event) {
    console.log('Clicked outside:', e);
  }
}

了解更多 > npm ng-click-outside


推荐阅读