Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close/Hide a dialog when area outside of dialog is clicked

Tags:

angular

I have an Angular app that has a pop-up dialog where a user can enter some information. I would like to have this dialog close or become hidden when any area in the application, other than the pop-up dialog, is clicked. This way the user can enter data as needed and only when the click outside of the pop-up dialog will it close.

I could use the (mousleave) event but I only want the pop-up dialog to be hidden when the user clicks somewhere in the main application (other than the pop-up dialog). In the image below that would mean anywhere in the blue area.

example layout of application

UPDATE: The biggesr difficulty for me is figuring out how to capture the click event in the main application (blue area) only.

like image 692
webworm Avatar asked Nov 19 '25 11:11

webworm


1 Answers

You can create a ClickOutside directive so that you can listen click events and check if its target is your target. You can check out this page to create a custom directive.

In your directive, you can use @HostListener() to listen click events:

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

Then in your template, you can use:

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

And in your component you can add/remove css classes or create/destroy the DOM element. In this case, I assume you defined your popup with @ViewChild() popup: ElementRef in your component:

hidePopup = () => {
    this.popup.nativeElement.classList.add("hidden");
    /*
     * Or you can do some other stuff here 
     */
}
like image 110
Harun Yilmaz Avatar answered Nov 21 '25 01:11

Harun Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!