-1

I'm working on an Angular 7 app. I added an icon that the user can click on, and when they click on it, an absolutely positioned div appears like a tooltip. The tooltip is encapsulated in an Angular component.

I need to make the tooltip disappear when the user clicks anywhere on the page outside of the tooltip. It seems that I need to somehow add a universal event handler on the whole page that catches mouse clicks and somehow checks to see if the tooltip is open and whether or not the click event was on the tooltip, but I do not know how to do this within the component model of Angular.

How do I make it so that when the user clicks on the page outside of the tooltip, the tooltip disappears?

I should add that I can't simply add an invisible div that covers the page behind the tooltip and listen for clicks on that because then the user wouldn't be able to click on other page elements.

Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • Something like this perhaps? https://stackoverflow.com/questions/40107008/detect-click-outside-angular-component – eko May 07 '21 at 16:24
  • @eko, it sounds like the `HostListener` that you refer to only gets triggered on the parent component, but elsewhere on the page, it won't work. – Vivian River May 07 '21 at 16:44

1 Answers1

0

You can try to bind to the focusout event of your absolutely positioned div or your tooltip, and then when it fires, call a method in your component that will set a variable in your component.

in your tooltip, you can bind to that variable and check its value to hide your tooltip depending on the value of that variable.

another approach would be - instead of using a mere variable and if you are using state management, you can publish an event from your absolutely positioned div and subscribe to that state property in your tooltip component, so that changes can be caught by that tooltip component so that you can set a component variable in that tooltip and then bind to that variable in your template,

Gian Marco Te
  • 112
  • 1
  • 2
  • 14