NOTE: for those who want to use web workers, and you need to avoid using document and nativeElement, this will work.
I answered the same question here: stack overflow
Copy / Paste the link above:
I had the same problem when I was making a drop down menu and confirmation dialog, I wanted to reject them when clicking outside.
My final implementation works fine, but requires CSS3 animation and style.
NOTE : I have not tested the code below, there may be some syntax problems that need to be fixed, as well as obvious adjustments for your own project!
What I've done:
I made a separate fixed div with a height of 100%, a width of 100% and transformed: scale (0), this is essentially a background, you can style it with background-color: rgba (0, 0, 0, 0.466); to make it clear that the menu is open and the background is closing. The menu gets the z-index higher than everything else, then the background div gets the z-index lower than the menu, but also higher than everything else. Then the background has a click event that closes the drop-down list.
Here it is with your HTML code.
<div class="dropdownbackground" [ngClass]="{showbackground: qtydropdownOpened}" (click)="qtydropdownOpened = !qtydropdownOpened"><div> <div class="zindex" [class.open]="qtydropdownOpened"> <button (click)="qtydropdownOpened = !qtydropdownOpened" type="button" data-toggle="dropdown" aria-haspopup="true" [attr.aria-expanded]="qtydropdownOpened ? 'true': 'false' "> {{selectedqty}}<span class="caret margin-left-1x "></span> </button> <div class="dropdown-wrp dropdown-menu"> <ul class="default-dropdown"> <li *ngFor="let quantity of quantities"> <a (click)="qtydropdownOpened = !qtydropdownOpened;setQuantity(quantity)">{{quantity }}</a> </li> </ul> </div> </div>
Here is css3 that needs some simple animations.
.zindex{ z-index: 3; } .dropdownbackground{ width: 100%; height: 100%; position: fixed; z-index: 2; transform: scale(0); opacity: 0; background-color: rgba(0, 0, 0, 0.466); } .showbackground{ animation: showBackGround 0.4s 1 forwards; } @keyframes showBackGround { 1%{ transform: scale(1); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }
If you don’t need anything visual, you can simply use such a transition
.dropdownbackground{ width: 100%; height: 100%; position: fixed; z-index: 2; transform: scale(0); opacity: 0; transition all 0.1s; } .dropdownbackground.showbackground{ transform: scale(1); }