0

We can follow this approach Detect click outside element? in Angular as well with HostListner.

In my component I have registered a host listener which listens on document click and hide the menu inside my component. This approach works fine with a single component. However I am a bit concerned about the performance when the component is instantiated(in a list) 100 times each component registers document on click and do some processing to hide the menu opened from its component if any.

I can move the code outside the component list but then I need to hold references of each component to detect which one has opened menu and should be closed.

None of these two approach is perfect is there some other way to handle this efficiently as well as without leaking the component code in its parent?

Deepak Sharma
  • 1,873
  • 10
  • 23
  • need more information on the menu probably.. is it a shared menu? like a slide-in and slide-out side menu? if that is the case, I think you can just make the menu covers the whole page and make the area outside the menu item transparent, then register event on the transparent area. – Surely Oct 13 '17 at 15:03
  • Its not a shared menu its a component specific menu like an menu with open and edit and share that appears when we click on the component – Deepak Sharma Oct 13 '17 at 15:12

1 Answers1

0

Instead of setting the HostListener on the component, use it in a directive and set it on that component's wrapper. The wrapper could be an ng-container if you wish to not have template modification.

Vega
  • 27,856
  • 27
  • 95
  • 103