angular - 在Angular的网页上单击外部时如何折叠展开的下拉菜单?
问题描述
我们创建了用于扩展和折叠 bootstrap 4 导航栏下拉菜单的指令。每次用户单击它时,它都会切换,在展开和折叠状态之间移动。当展开并且用户导航到另一个区域页面时,它保持展开状态。例如,在网页的其他部分单击下拉按钮区域之外时,如何强制它折叠?这是指令:
TS
constructor(private _el: ElementRef) { }
@HostBinding('class.show') isOpen = false;
@HostListener('click') toogleOpen() {
this.isOpen = !this.isOpen;
this._el.nativeElement.querySelector('.dropdown-menu').classList.toggle('show')
}
}
HTML
<li *ngIf="isLogged" class="nav-item dropdown ml-auto" appdropdown #r="appdropdown">
...
...
</li>
如何通过单击网页的其他部分来关闭打开的下拉菜单?
解决方案
html:
<button (click)="onClick($event)"></button>
组件(打字稿):
public clicked: boolean = false;
public onClick(event): void {
event.preventDefault();
event.stopPropagation();
this.clicked = true;
}
@HostListener('document:click', ['event'])
private clickedOutside(event): void {
if (this.clicked) {
this._el.nativeElement.querySelector('.dropdown-menu').classList.toggle('show')
}
}
希望我的帮助有效ツ</p>
推荐阅读
- python - 如何在问题框中添加错误消息?
- java - 在 Java 中更改 Google IAM 的用户代理
- arduino - Arduino OTA 固件备份 ESP32
- google-apps-script - 侧边栏功能
- c - 如何使用 [-a,a] 范围内的 libsodium 在 C 中生成均匀分布的随机双精度数?
- php - 在 Json:api 规范中包含具有相同 id 和类型的关系
- vba - Obeject_Worksheet 杀死代码的方法范围 - 有什么问题?
- facebook-graph-api - 在 Facebook Graph API 上调用 /{page-id}/ads_posts 需要什么权限?
- sql-server - 如何在使用表的同时更新表?
- bash - 将具有特殊字符的变量字符串存储到bash中的数组中