angular - 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 指令。对于在下拉菜单或模态对话框之外点击做出反应的事情很有用。
第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
推荐阅读
- jenkins - Sonar Scanner 选项可将项目属性值包含在脚本化管道本身中
- java - Ant get 任务无法从 https 端点下载
- c++builder - 如何使用 Windows 鼠标挂钩 API 函数在 C++ Builder 应用程序中挂钩鼠标事件?
- ios - 如何在目标c中记录电话
- java - 如何使用 JInternalFrame 标题栏更改颜色?
- javascript - 我将如何编写一个递归函数来对使用尾调用优化 (TCO) 的数字数组求和?
- angular - 有没有办法使组件(而不是元素)以角度拖动?
- php - PHP 容器未在 docker 中启动
- xcode - 如何在 Xcode10.2 中运行命令行工具项目
- python - 如何向我的数组添加新的复杂值?