Outside Click

import { Directive, Input, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';

  selector: '[clickOutside]',
export class ClickOutsideDirective {

  @Output() clickOutside = new EventEmitter<void>();

  constructor(private elementRef: ElementRef) { }

  @HostListener('document:click', ['$event.target'])
  public onClick(target) {
    const clickedInside = this.elementRef.nativeElement.contains(target);
    if (!clickedInside) {
<div (clickOutside)="someHandler()"></div>

Keydown of Component

  @HostListener('document: keydown', ['$event'])
  public onEnter(event: KeyboardEvent): void {
    if (this.elementRef.nativeElement.contains(event.target)) {
      if (event.code === 'Enter') {
        // TODO:


If the element contains *ngIf, this.overlay.nativeElement.contains(event.target); always return false. Because of the angular directive *ngIf

<div #overlay>
	<div *ngIf="show" class="item">
		Click here
@ViewChild('overlay', { static: false }) overlay: ElementRef;

this.overlay.nativeElement.contains(event.target);  // always return false

How to solve it?

You can check the event.target


Or use [hidden] instead.

	<div [hidden]="!show" class="item">
		Click here