Home > Back-end >  Is there any way to close the modal popup on click of outside in angular?
Is there any way to close the modal popup on click of outside in angular?

Time:10-17

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

CodePudding user response:

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
}

CodePudding user response:

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";
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

@HostListener('document:click', ['$event'])
  onDocumentClick(event: MouseEvent) {
   console.log(event.target)
  }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

  • Related