Angular 7/8 | Hide Div on Click Ouside Angular Tutorial

In this tutorial, we will learn how to trigger click events on an element when we click outside of that element container in Angular.

We used to have a target element in JQuery using which we could have easily detected if the clicked element is the same element or its outside that element.

In Angular, we will use a nice package module called ng-click-outside which provides a directive component to trigger click event when we click outside of an element with click event bindings.

 

Let’s check it out in details:

Here we assume that you already have an Angular 2+ version project up and running, if not you can easily create one using Ng CLI tool and run following command in terminal:

 

Install ng-click-outside

To add Click Outside directive we will install the ng-click-outside package by running following NPM command in terminal:

Import in App Module

To use this directive globally in application components, open app.module.ts file then import ClickOutsideModule and also add in imports array as shown below:

How to Use ClickOuside Directive?

To trigger event on click outside on container you simply need to define (clickOutside) on the element as shown below:

Update component class with the following code:

Also, add the following CSS in app.component.css file:

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of