首页 > 解决方案 > 在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>

如何通过单击网页的其他部分来关闭打开的下拉菜单?

标签: angulartypescriptdropdown

解决方案


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>


推荐阅读