Angular 2 addEventListener inside 指令

Angular 2 addEventListener inside directive

我正在写 Angular 2 应用程序,在里面我有写在 Bootstrap

上的下拉菜单
<li class="dropdown" dropdown>
    <a class="dropdown-toggle" data-toggle="dropdown">
       User <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" aria-labelledby="download">
       <li><a routerLink="/user/profile">My Profile</a></li>
       <li><a (click)="logout()">Log Out</a></li>
    </ul>
</li>

我只想写下一个用于切换菜单的小指令。到此结束:

@Directive({
    selector: "[dropdown]"
})
export class DropdownDirective implements OnInit {

    private isOpen = false;
    private defaultClassName: string;

    @HostListener('click') toggle() {            

    let that = this;

    if (!this.isOpen) {

        this.elRef.nativeElement.className = this.defaultClassName + " open";

        document.addEventListener("click", () => {             
            that.elRef.nativeElement.className = that.defaultClassName;
            that.isOpen = false;
            document.removeEventListener("click");
        });

        this.isOpen = !this.isOpen;
    }


    }

    constructor(private elRef: ElementRef) {

    }    

    ngOnInit(): void {
        this.defaultClassName = this.elRef.nativeElement.className;
    }

}

看起来不错。但不起作用。经过短暂的调试后,我发现添加到文档中的事件侦听器在分配后立即触发。

document.addEventListener("click", () => {
                    that.elRef.nativeElement.className = that.defaultClassName;
                    that.isOpen = false;
                    document.removeEventListener("click");
});

事实菜单在打开后立即关闭。如何解决它以及为什么会发生这种情况?

我已经用 @HostListener() 解决了同样的情况。在包含下拉菜单的组件上:

@HostListener('document:click', ['$event'])
private clickAnywhere(event: MouseEvent): void {
 if (this.IsSelected && !this.elementRef.nativeElement.contains(event.target)) {
  this.IsSelected = false;
 }
}

this.IsSelected 是我用来显示下拉列表的绑定 属性。 if()中的条件一般是检查用户是否点击了菜单或文档正文。

确保将 elementRef 注入到构造函数中,以便您可以访问呈现的 HTML 以检查是否是单击的内容: public constructor(private elementRef: ElementRef) { }

您可以找到有关 HostListener 的更多信息here