防止点击关闭对话框

时间:2017-09-11 21:56:31

标签: javascript html twitter-bootstrap angular

这是我的对话

<div *ngIf="visible" class="overlay" (click)="close()">
    <div role="dialog" class="overlay-content">
        <div class="modal-dialog" (click)="$event.stopPropagation()">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" (click)="close()" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Confirmation</h4>
                </div>
                <div class="modal-body">
                    <ng-content></ng-content>
                </div>
                <div class="modal-footer footer-buttons">
                    <button type="button" class="btn btn-default" (click)="confirm()">OK</button>
                    <button type="button" class="btn btn-default" (click)="close()">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>

正如您可能会看到大多数上部div有(click)="close()",当单击对话框外部时会关闭forse对话框,因为当单击对话框内部时,下一个div (click)="$event.stopPropagation()"会停止,但此解决方案是错误的。问题是,如果我在对话框中放置任何选项卡,则由于(click)="$event.stopPropagation()而更改选项卡不起作用。有谁知道更好的解决方案吗?换句话说,如何在对话框外单击关闭对话框,但在单击内部时保持打开状态?

2 个答案:

答案 0 :(得分:1)

我猜你正在寻找一个会听取对话点击外部的指令。 这是我的版本:

@Directive({
    selector: '[clickOutside]'
})
export class ClickOutsideDirective {
    constructor(private elementRef: ElementRef) {
    }

    @Output()
    clickOutside = new EventEmitter<Event>();

    @HostListener('document:click', ['$event', '$event.target'])
    onClick(event: MouseEvent, targetElement: HTMLElement): void {
        if (!targetElement) {
            return;
        }

        const clickedInside = this.elementRef.nativeElement.contains(targetElement);
        if (!clickedInside) {
            this.clickOutside.emit(event);
        }
    }
}

并将其用作以下内容:

<div *ngIf="visible" class="overlay" (clickOutside)="visible=false">
....

DEMO

答案 1 :(得分:1)

一种选择是不嵌套叠加层和叠加内容。

例如:

<div class="overlay"></div>
<div class="overlay-content">/* Content */</div>

的CSS:

.overlay {
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
z-index: 5;
background-color: rgba(0,0,0,.6);
}

.overlay-content {
background: white;
position: fixed;
width: 50%;
height: 50%;
margin-left: 25%;
margin-top: 5%;
z-index: 10;
}

codepen:https://codepen.io/bgraham626/pen/VMZxON