From 8b0a7453589cc064c33dda063ce9e328c6681737 Mon Sep 17 00:00:00 2001 From: francesco Date: Tue, 14 Dec 2021 17:43:03 +0100 Subject: [PATCH] Dropdown closing by clicking anywhere else --- project/src/app/shared/dropdown.directive.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/project/src/app/shared/dropdown.directive.ts b/project/src/app/shared/dropdown.directive.ts index 698a07f..caea714 100644 --- a/project/src/app/shared/dropdown.directive.ts +++ b/project/src/app/shared/dropdown.directive.ts @@ -1,12 +1,12 @@ -import { Directive, HostListener, HostBinding } from '@angular/core'; - +import {Directive, ElementRef, HostBinding, HostListener} from '@angular/core'; + @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { @HostBinding('class.open') isOpen = false; - - @HostListener('click') toggleOpen() { - this.isOpen = !this.isOpen; + @HostListener('document:click', ['$event']) toggleOpen(event: Event) { + this.isOpen = this.elRef.nativeElement.contains(event.target) ? !this.isOpen : false; } + constructor(private elRef: ElementRef) {} } \ No newline at end of file