0

I want to detect click events outside of an angular component so my program knows to close a custom dropdown I created.

I tried:

https://github.com/monsterlessonsacademy/monsterlessonsacademy/tree/204-angular-dropdown-menu-close-on-click-outside

Doesn't work for unknown reason. I attached clickOutside (clickOutside)="clickedOutside()" to my dropdown component with the code from clickOutside.directive.ts imported in App Module. I cannot believe this is the solution either as it is ~35 lines and a separate file to detect a click event.

The next solution ("solution") up on the chopping block is to use HostListener:

Detect click outside Angular component

This is bad IMO because, as the 2nd answer says, it is costly on performance and will likely lag my application.

Here is the third option

How can I close a dropdown on click outside?

@Component({
  host: {
    '(document:click)': 'closeDropdown()',
  },
})
class SomeComponent() {

  show: boolean = false;

  closeDropdown(): void {
    console.log(47, this.show, this.type, "clicked outside");
    this.show = !this.show;
  }
}

This didnt work for me because the click event registers for all dropdowns and tries to, therefore, apply the same action to every dropdown, regardless of whether I am clicking to open the dropdown or to close it.

Is there no option that is performant and will allow me to close all other dropdowns while opening the one I am clicking to open? surely it can be done without some edge case solution like the 2nd or third option

plutownium
  • 69
  • 1
  • 6

0 Answers0