title: HostListener on outside click Angular 6
body: <p>This is my way to open a popover:</p>
  
  
  
  <pre class="lang-html prettyprint-override"><code>&lt;div&gt;
    &lt;a (click)="trigger = true"&gt;
      &lt;div&gt;
        &lt;i class="pe-7s-file"&gt;&lt;/i&gt;
      &lt;/div&gt;
    &lt;/a&gt;
    &lt;div popover clickOutside (clickOutside)="console.log('Outside')" *ngIf="trigger==true"&gt;
      &lt;p&gt;Hello Popover&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>When I click on first div it prints (outside) in my console, I want to open the popover at first time without any message on console, and when I click outside popover div the console should print.</p>
  
  <p>This is my hostlistener:</p>
  
  
  
  <pre class="lang-ts prettyprint-override"><code>@Directive({
      selector: '[clickOutside]'
  })
  export class ClickOutsideDirective {
  
      constructor(private _elementRef: ElementRef) { }
  
      @Output('clickOutside') clickOutside: EventEmitter&lt;any&gt; = new EventEmitter();
  
      @HostListener('document:click', ['$event.target'])
      onMouseEnter(targetElement) {
          const clickedInside = this._elementRef.nativeElement.contains(targetElement);
          if (!clickedInside) {
              this.clickOutside.emit(null);
          }
      }
  
  }
  </code></pre>