Recommand · October 16, 2021 0

Is there any way to close the modal popup on click of outside in angular?

I have a modal popup made with only html css no bootstrap or other plugins. I need to close the popup on click of outside using angular . Note that once the popup opens background will be greyed out and we can’t click any things outside popup. This popup is inside a whole page container.
I tried this but didn’t work.How to use host listener for detecting outside click

you can use blur event on main div

<div id="main" (blur)="dropFunction()" ngIf="showMainDiv">
...
</div>

dropFunction(){
 this.showMainDiv = false; // same logic to enable backdrop  also
}

you can use the window onclick event & inside that, you can check is that target is your modal or not

var modal = document.getElementById("myModal");
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

you can use the below code corresponding to window onclick event in angular

@HostListener('document:click', ['$event'])
  onDocumentClick(event: MouseEvent) {
   console.log(event.target)
  }

I will assume that the modal container has a class added on it.

<div class="app-modal-container">
  // your modal content here
</div>

Then we will listen to click events at the document level,

@HostListener('document:click')
click($event: Event) {

}

Then any click originated from inside the modal will have the div with class app-modal-container.

Use the composedPath() method on $event to get the path, iterate all the elements in the path, and check if the required div is present. If not the click was on outside.