In one of my components, I have implemented a feature where clicking on an image toggles a boolean variable to show or hide a menu. The HTML structure for this functionality is as follows:
<img src="../../assets/image/dropdown.png" class="dropdown-image" (click)="toggleDropDownMenu()">
<div class="dropdown-content" [hidden]="dropDownMenu">
<a class="menu-item" (click)="showTerms()">Policy</a>
<a class="menu-item" (click)="showProfile()">Profile</a>
<a class="menu-item" (click)="logOut()">Log Out</a>
</div>
The toggleDropdownMenu() function simply switches the value of the variable:
public toggleDropDownMenu(): void {
this.dropDownMenu = !this.dropDownMenu;
}
This setup allows the user to control the visibility of the menu by clicking on the image. However, I wanted to enhance this functionality by also hiding the menu when the user clicks outside of it. After some research, I discovered the concept of directives and decided to implement it in the following way:
import { Directive, ElementRef, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
console.log("clicked inside");
} else {
console.log("clicked outside");
}
}
constructor(private eRef: ElementRef) {
console.log(" not clicked");
}
}
This directive successfully detects whether a click event occurred inside or outside the designated element. My goal now is to utilize this directive in my HTML code like this:
<img src="../../assets/image/dropdown.png" class="dropdown-image" (click)="toggleDropDownMenu()"
(clickOutside)="closeMenu()">
<div class="dropdown-content" [hidden]="dropDownMenu">
<a class="menu-item" (click)="showTerms()">Policy</a>
<a class="menu-item" (click)="showProfile()">Profile</a>
<a class="menu-item" (click)="logOut()">Log Out</a>
</div>
Is there a way to achieve this integration between the clickOutside directive and the menu toggling functionality?
Can anyone provide an example or suggest a solution?