Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  171] [ 6]  / answers: 1 / hits: 15608  / 6 Years ago, sat, july 21, 2018, 12:00:00

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


More From » angular

 Answers
3

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


[#53920] Wednesday, July 18, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marques

Total Points: 366
Total Questions: 108
Total Answers: 111

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
marques questions
;