kosnkov
kosnkov

Reputation: 5941

prevent closing dialog on click

this is my dialog

<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>

as you might see most upper div has (click)="close()" which forses dialog to close when clicking outside the dialog, because next div has (click)="$event.stopPropagation()" it stops when clicking inside the dialog, but this solution is wrong. The problem is that if I put any tabs inside the dialog, then changing tabs does not work because of (click)="$event.stopPropagation(). Does anyone know better solution for this ? In other words how to close dialog clicking outside the dialog, but keep it open when clicking inside ?

Upvotes: 1

Views: 1036

Answers (2)

Vega
Vega

Reputation: 28708

I am guessing you are looking for a directive which will listen to the outside of the dialog clicks. Here is my version:

@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);
        }
    }
}

and use it as the following:

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

DEMO

Upvotes: 1

bgraham
bgraham

Reputation: 1997

One options is to not nest the overlay and overlay-content.

For example:

<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

Upvotes: 1

Related Questions