ttmt
ttmt

Reputation: 4984

Angular 4 drop down menu click away to close

I have a demo here - https://stackblitz.com/edit/angular-lewrxv?file=app%2FClickElsewhereDirective.ts

I have a drop down menu that opens when the button is clicked.

Id like to close the menu when you click anywhere else.

I'm using a directive to emit an event when I click outside the menu.

The console log works before the event is emitted, but how can I use this to close the menu.

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

@Directive({ selector: '[clickElsewhere]' })

export class ClickElsewhereDirective {
  @Output() clickElsewhere = new EventEmitter<MouseEvent>(); 

  constructor(private elementRef: ElementRef) {}

  @HostListener('document:click', ['$event'])
  public onDocumentClick(event: MouseEvent): void {
    const targetElement = event.target as HTMLElement;

      // Check if the click was outside the element
      if (targetElement && !this.elementRef.nativeElement.contains(targetElement)) {
         console.log(event) 
         this.clickElsewhere.emit(event);
      }
  }
}

Upvotes: 1

Views: 3263

Answers (1)

Tam&#225;s Szab&#243;
Tam&#225;s Szab&#243;

Reputation: 1418

You have to subscribe to your directives' events like so:

(clickElsewhere)="closeDropdown()"

You may have to adjust your div sizes, margins, etc. but it will work.

Here is the updated demo: https://stackblitz.com/edit/angular-qumejg

Upvotes: 1

Related Questions