简体   繁体   English

如何在外部单击以隐藏div?

[英]How to hide a div by clicking outside it?

I know there are many such solutions on jQuery. 我知道jQuery有很多这样的解决方案。 But so far I can not adapt these solutions for myself with the help of Angular. 但是到目前为止,我无法在Angular的帮助下适应这些解决方案。 I have an isOpenSharedLinkDiv variable that uses * ngIf to show or hide a div. 我有一个使用* ngIf来显示或隐藏div的isOpenSharedLinkDiv变量。 I try to translate this value to false when I click outside of this div, but in this case the div does not open at all. 当我在该div之外单击时,我尝试将此值转换为false,但是在这种情况下,该div根本不会打开。 I think I'm missing something. 我想我缺少了一些东西。

test() {
    console.log(this.isOpenSharedLinkDiv);
    // const div = document.querySelector('#sharing-basket-div');
    const div = document.querySelector('.page');
    // const icon = document.querySelector('#sharing-basket-icon');
    const shareDiv = document.querySelector('#share');

    div.addEventListener('click', ev => {
      if (ev.target !== shareDiv || ev.target === div && this.isOpenSharedLinkDiv === true) {
        // this.isOpenSharedLinkDiv = false;
        console.log(ev.target);
        console.log(this.isOpenSharedLinkDiv);
      } else {
        return;
      }
    });
  }

As a result, this variable turns out to be false, even when it is not open yet. 结果,即使尚未打开该变量,其结果仍为false。

You can use a really simple directive to do this: 您可以使用一个非常简单的指令来执行此操作:

import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: '[clickOutside]'
})
export class UnoClickOutsideDirective {
  constructor(private elementRef: ElementRef) {}

  @Output() clickOutside: EventEmitter<null> = new EventEmitter<null>();

  @HostListener('document:click', ['$event.target']) onMouseEnter(targetElement) {
    const clickedInside = this.elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.clickOutside.emit(null);
    }
  }
}

This directive applied to any element, tells you when you click outside of it. 该指令适用于任何元素,告诉您何时单击它。 So you can use it with a div like this: 因此,您可以将其与如下所示的div一起使用:

component.html component.html

<div *ngIf="condition" (clickOutside)="condition=false"></div>

component.ts component.ts

condition: boolean = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM