user944513
user944513

Reputation: 12729

how to close pop screen when use click outside in angular 4?

could you please tell me how to close pop screen when use click outside in angular 4 ?In my demo application I have one button on click of button I am showing pop up screen (which is working find).I want it should close when User click outside but not on pop up screen in other words it should close when user click other than pop up screen .I try to make directive which detect click outside or inside but it not work for me here is my code

import { Directive,ElementRef } from '@angular/core';

@Directive({
  selector: '[appOutside]',
   host: {
   '(document:click)': 'onClick($event)',
  }
})
export class OutsideDirective {

  constructor(private elementRef: ElementRef) { }

  onClick(event) {
   if (!this.elementRef.nativeElement.contains(event.target)) // or some similar check
     alert('clicked')
     //doSomething();
  }

}

https://stackblitz.com/edit/angular-1xhibr?file=src%2Fapp%2Foutside.directive.ts

Upvotes: 2

Views: 18890

Answers (2)

user184994
user184994

Reputation: 18281

All you actually need to do is move the appOutside directive onto your modal, since we want to know if the click is outside of the modal. If you leave it on the hover_bkgr_fricc div, it will always be inside, since it's styled to take up the whole viewport

<div class="hover_bkgr_fricc" *ngIf="ispopUpShow" >
    <span class="helper"></span>
    <div appOutside>
        <div class="popupCloseButton">X</div>
        <p>Add any HTML content<br />inside the popup box!</p>
    </div>
</div>

That change alone should work.

Here is a fork with the change I made

Upvotes: 1

Shantanu
Shantanu

Reputation: 3513

Just add class to DOM nodes of popup & outside of popup (or on appOutside element). Then just checkif click event triggered on DOM part inside of popup or outside. Update your view code to:

<div class="hover_bkgr_fricc" *ngIf="ispopUpShow" appOutside (click)="ClickedOut($event)">
    <span class="helper"></span>
    <div class="inside-popup">
        <div class="popupCloseButton" (click)="closePop()">X</div>
        <p>Add any HTML content<br />inside the popup box!</p>
    </div>
</div>

Where those methods in component class can be:

closePop() {
    this.ispopUpShow = false;
 }

 ClickedOut(event) {
    if(event.target.className === "hover_bkgr_fricc") {
      this.ispopUpShow = false;
    } 
 }

Updated Stackblitz Example

Upvotes: 2

Related Questions