Detect Click outside element in angular 4 using directives Detect Click outside element in angular 4 using directives angular angular

Detect Click outside element in angular 4 using directives


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