2017-06-13 59 views
0

我写角2应用程序和里面我已经写上引导角2的addEventListener内部指令

<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"); 
}); 

作为一个事实菜单,它刚刚打开后关闭。如何解决它,为什么会发生这种情况?

回答

2

我已经用@HostListener()解决了同样的情况。在零件保持下拉:

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

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

确保注入elementRef到构造这样你就可以访问所提供的HTML,以检查是否是被点击了什么: public constructor(private elementRef: ElementRef) { }

你可以找到更多关于HostListener here

+1

谢谢。这解决了我的问题! – dantey89