'Hide overlaypanel when I click outside the box or in the box Angular 4
I have created an OverlayPanel like component so there I can put more clicks or something else. But when I click outside the overlay or in the overlay this does not exit stays always there, it is dissapear only when I click in button what I have writed.
Here is the link of the StackBlitz
I have like this the overlaPanel created.
<div class="dropdown">
<div (click)="toggle()" class="body">
<ng-content select="[body]"></ng-content>
</div>
<div *ngIf="active" class="popup" >
<ng-content select="[popup]"></ng-content>
</div>
</div>
.dropdown {
position: relative;
display: inline-block;
}
.popup {
display: block;
position: absolute;
z-index: 1000;
}
export class OverlaypanelComponent implements OnInit {
active = false;
constructor() {
}
offClickHandler(event: any) {
if (event['.body'] && event['.popup'] === true) {
this.active = false;
}
}
ngOnInit(): void {
}
toggle() {
this.active = !this.active;
}
close() {
this.active = !this.active;
}
}
And this is when I call this component
<app-overlaypanel>
<div body [ngClass]="[getBackgroundColorClass(),clazz]" class="fa fa-pencil-square-o edit-block"></div>
<div class="overlayPopup" popup>
<div class="dropdown-menu-item" (click)="openTechnicalEditDialog({cluster: cluster, type: clazz})">Edit</div>
<div class="dropdown-menu-item" (click)="delete()">Delete</div>
<div class="dropdown-menu-item" (click)="openTechnicalEditDialog({appendToParentId: cluster.id})" *ngIf="cluster.level <= 9">Append</div>
<div
class="dropdown-menu-item" (click)="clicked.emit()">Assign</div>
</div>
</app-overlaypanel>
Solution 1:[1]
You can use ng-click-outside
module as described here https://www.npmjs.com/package/ng-click-outside
working with me fine in angular 8
Solution 2:[2]
I know the question says Angular 4 but incase if someone is wondering how can we do the same with latest version of angular.
Now Anglar Material overlay comes with such directive and event listener.
<ng-template
cdkConnectedOverlay
[cdkConnectedOverlayOrigin]="trigger"
[cdkConnectedOverlayOpen]="isOpen"
[cdkConnectedOverlayHasBackdrop]="isOpen"
[cdkConnectedOverlayBackdropClass]="'cdk-overlay-transparent-backdrop-cs'"
(backdropClick)="isOpen = !isOpen"
>
content to be shown on overlay
</ng-template>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hazem Abdelwahab |
Solution 2 | Santosh |