Detecting click inside and outside of the listening component in Angular

38 Views Asked by At

I have a search box and show a filterable list of matching elements in a DIV that hovers over the other components. Once the user selects something, the DIV is hidden. This part works as supposed to. Occasionally, the user will desire to cancel the lookup process and click on a cross icon in the popout. This works as expected too.

Now, I'd like to enable the user to hide the popout if they click outside of it. The approach I picked was to implement a host listening method as shown below.

@HostListener('click', ['$event']) onClickHost() {
  this.projectToggle = false;
  this.userToggle = false;
}

Well... it works as supposed to with a huge "butt". Clicking outside the listening component (which by definition is outside the popout part), gives me no action. Naturally, I understand why it won't react - the host listened to is not being clicked, du'h...

The best solution I can think of is to let the parent component (the page itself containing the popouting search box) listen to its host and propagate such an event into the child. It's rather significant increment in complexity and I want to find a simpler way to detect: click anywhere on the page outside of the DIV that poopouted.

Is it possible? If not, I'll tell the user to be happy with the cross to click. I just wish to establish that it's not my ignorance that sets the limit, not my laziness.

0

There are 0 best solutions below