[英]Click detection outside A conditioned HTML element - Angular 6
I have a custom select that appears conditionally in the DOM. 我有一个自定义选择,有条件地出现在DOM中。 I trying to detect the user clicks outside the element and remove the element from the DOM.
我试图检测用户在元素外部单击并从DOM中删除该元素。 Better i show you what appears to be the problem
更好的是,我向您展示似乎是什么问题
HTML HTML
<div class="worker-info">
<div (click)="showWorkersSelect = !showWorkersSelect" class="worker-name">
<fa-icon [icon]="['fal', 'user-circle']" size="1x"></fa-icon>
Worker name: <span>Anna</span>
<fa-icon class="select-worker-icon" [icon]="['fal', 'caret-down']" size="1x"></fa-icon>
</div>
<div #workerSelection @showWorkersSelect *ngIf="showWorkersSelect" class="select-worker-menu">
<div (click)="showWorkersSelect = !showWorkersSelect" class="select-worker-menu__worker-name">
Essti
</div>
<div (click)="showWorkersSelect = !showWorkersSelect"class="select-worker-menu__worker-name">
Ilana
</div>
</div>
</div>
So when the user clicks here 因此,当用户单击此处时
<div (click)="showWorkersSelect = !showWorkersSelect" class="worker-name">
The showWorkersSelect
becoming true
and the selection appers. showWorkersSelect
变为true
,并且选择生效。
TS TS
@ViewChild('workerSelection') workerSelection: ElementRef
public showWorkersSelect = false
@HostListener('document:click', ['$event', '$event.target'])
onClick(event: MouseEvent, targetElement: HTMLElement): void {
if (this.showWorkersSelect) {
if (!targetElement) {
return;
}
const clickedInside = this.workerSelection.nativeElement.contains(targetElement);
if (!clickedInside) {
this.showWorkersSelect = false;
}
}
}
Here I want to run the method only when the selection is shown and close it after the user clicks outside, but the method closing it immediately after it opens 在这里,我只想在显示选择内容时运行该方法,并在用户单击外部后将其关闭,但是将其打开后立即将其关闭的方法
If your worker-selection has a z-index>0, You can use a "div" between with a z-index between 0 and z-index of worker-selection that cover all the screen 如果您的工人选择的z-index> 0,则可以在z-index介于0和工人选择的z-index之间的范围内使用“ div”,它覆盖了整个屏幕
<div class="backscreen" *ngIf="showWorkersSelect" (click)="showWorkersSelect=false">
.backscreen {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040; //<--use a z-index between 0 and z-index of selectWorker
background-color: transparent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.