Detect Click outside element in angular 4 using directives

那年仲夏 提交于 2019-12-03 00:09:24

There are few changes in relation to your plnkr.

  1. NgModules, or rather take a look on Archietcture of the framework. The module is the place where you should register your components, services and directices
  2. Once you registered your directive inside module you don't have to import it inside components

The directive itself looks fine for me. I compared your directive with mine that works fine in Angular 4.3.5.

Actually, you don't need any directive in that case, unless it won't be used repetitive. If you need to apply that clickOutside only for menu it would be better to do sth like that:

Bind click event to your "inside" selector like that. Let's say it's your menu:

  <ul id="menu" (click)="clickedInside($event)"> <li> .. </li> </ul>

then inside your component add clickedInside() function like this:

  clickedInside($event: Event){
    $event.preventDefault();
    $event.stopPropagation();  // <- that will stop propagation on lower layers
    console.log("CLICKED INSIDE, MENU WON'T HIDE");
  }

And finally you can use Host Listener in your component to bind click also to the rest of document

  @HostListener('document:click', ['$event']) clickedOutside($event){
    // here you can hide your menu
    console.log("CLICKED OUTSIDE");
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!