代码之家  ›  专栏  ›  技术社区  ›  webworm

单击对话框外部区域时关闭/隐藏对话框

  •  0
  • webworm  · 技术社区  · 6 年前

    我有一个有角度的应用程序,它有一个弹出对话框,用户可以在其中输入一些信息。单击应用程序中除弹出对话框以外的任何区域时,我希望关闭或隐藏此对话框。这样,用户可以根据需要输入数据,只有当弹出对话框的外部单击时,它才会关闭。

    我可以使用 (mousleave) 但我只希望当用户单击主应用程序中的某个位置(而不是弹出对话框)时隐藏弹出对话框。在下面的图片中,这意味着蓝色区域的任何地方。

    example layout of application

    更新:对于我来说,最大的困难是如何在主应用程序(蓝色区域)中捕获单击事件。

    3 回复  |  直到 6 年前
        1
  •  2
  •   Nick Wang    6 年前

    您的组件是不是走错了路?对话框应该在一个固定全屏元素的顶部打开,例如

    <div class="overlayer" style="display: fixed; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); z-index: 9999" onclick="closeYourDialog()">
        <div class="your-dialog">
            ...
        </div>
    </div>
    

    如果不喜欢上一层,可以将不透明度设置为0。

        2
  •  1
  •   Ashish Ranjan    6 年前

    您可以将此对话框用作模式(可能是引导程序 modal )当你点击外部的时候,它会在内部使用一个背景来收听和关闭模式。

    如果您想通过自己的HTML来完成,您可以创建自己的背景,并在背景上添加一个单击事件侦听器。诀窍是防止点击事件从对话框中冒泡出来。

    为背景添加一个DIV,如:

    <div *ngIf="customDialogOpen" class="customBackdrop" (click)="customDialogOpen = false">
    
    <dialog-component *ngIf="customDialogOpen"></dialog-component>
    
    
    .customBackdrop {
      bottom: 0;
      left: 0;
      margin: auto;
      position: fixed;
      right: 0;
      top: 0;
      z-index: 999;  // lower than the z index of your dialog but higher than rest of the document
    }
    

    现在,每当打开对话框时,请设置 customDialogOpen 你的旗帜 .ts 文件为真。

    为了所有 (click) 从对话框下的事件添加如下内容:

    <some-elemet  (click)="...(youFunctions); $event.stopPropagation()">
    

    更新

    我的回答是将backdrop作为兄弟添加,@incnick提供了一种更好的方法,您可以将完整的对话框作为固定元素与backdrop一起打开,只需添加一个额外的DIV即可停止所有单击事件的传播。

    <div class="customBackdrop" *ngIf="customDialogOpen" (click)="customDialogOpen = false">
        <div (click)="$event.stopPropagation()">
           <dialog-component></dialog-component>
        </div>
    </div>
    

    注:无需额外添加 stopPropagation() 在这个解决方案或第一个解决方案中,如果您有一个处理传播的外部DIV。

        3
  •  0
  •   Harun Yilmaz    6 年前

    您可以创建一个 ClickOutside 指令,以便您可以监听单击事件并检查其目标是否是您的目标。你可以退房 this page 创建自定义指令。

    在您的指令中,您可以使用 @HostListener() 要收听点击事件:

    @Directive({
      selector: '[clickOutside]'
    })
    export class ClickedOutsideDirective{
    
        @Output()
        clickOutside: EventEmitter<Event> = new EventEmitter<Event>();
    
        @HostListener('document:click', ['$event'])
        onClick(event) {
            if(!this.elemRef.nativeElement.contains(event.target)) {
            // Cliecked Outside
             this.clickOutside.emit(event);
            }
        }
    
        constructor(private elemRef: ElementRef) {
        }
    }
    

    然后在模板中,可以使用:

    <div (clickOutside)="hidePopup()">...</div>
    

    在组件中,您可以添加/删除CSS类或创建/销毁DOM元素。在这种情况下,我假设您用 @ViewChild() popup: ElementRef 在组件中:

    hidePopup = () => {
        this.popup.nativeElement.classList.add("hidden");
        /*
         * Or you can do some other stuff here 
         */
    }