And I think it is useful in many things. My initial thought was to attach a window.onclick handler when the drawer opens and if anything is clicked other than the drawer it should close the drawer. In our controller, we created the method that we wanted to be called on the click out event, and we use the event.closest (docs here) to find out if the clicked spot is within our targeted-class div. Instead of checking if elementRef contains event.target, I check if elementRef is in the path (DOM path to target) of the event. Is "I didn't think it was serious" usually a good defence against "duty to rescue"? The bool showEastPanel variable is what is used to open and close the east panel. The relevant piece of code from this sample is below. Right, but the element is inside document. Again, if you like to see the working demo, use this link: Stackblitz Demo. text box). ng-click-outside - npm What is the symbol (which looks similar to an equals sign) called? We include a toggle on a button that listens for a click event on itself (click)="toggle()", but we also want to toggle the menu whenever the user clicks outside of it. Unexpected uint64 behaviour 0xFFFF'FFFF'FFFF'FFFF - 1 = 0? Solution: use Element.closest () inside a document click event listener Element.closest () works its way to the top of the root of the DOM object to see if it can find a match for the query selector that was provided. Content Discovery initiative April 13 update: Related questions using a Review our technical responses for the 2023 Developer Survey. At the end the dropdown is never displayed. I created a (dropdownOpen) event which I listen to at my ng-select element component and call a function which will close all the other SelectComponent's opened apart from the currently opened SelectComponent. Hi Kumar, please, note that in my solution i use a directive, and using elementRef in a directive it is quite common and encouraged by angular team (. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. What is the difference between Promises and Observables? [duplicate], https://stackoverflow.com/a/779785/5869296, https://github.com/arkon/ng-click-outside, How a top-ranked engineering school reimagined CS curriculum (Ep. How do I access the $scope variable in browser's console using AngularJS? In this approach, you need to inject Renderer2 into your component constructor, which the Renderer2 lets us to listen to triggered events elegantly. How do I detect a click outside an element? How can I set the default value for an HTML