[英]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.我有一个只有 html css 没有引导程序或其他插件的模式弹出窗口。 I need to close the popup on click of outside using angular .
我需要使用 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 上使用模糊事件
<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您可以使用窗口 onclick 事件 & 在其中,您可以检查目标是否是您的模态
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您可以使用以下与 angular 窗口 onclick 事件相对应的代码
@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
.然后,来自模态内部的任何点击都将具有类
app-modal-container
的div
。
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.使用
$event
上的composedPath()
方法获取路径,迭代路径中的所有元素,并检查是否存在所需的 div。 If not the click was on outside.如果不是,点击在外面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.