Mr. A
Mr. A

Reputation: 111

How to hide an html element when clicked outside

I want to know a way in which when clicked outside an html element(in my case , please see my code), the tooltip should hide. I don't want to use 'ng-clicked-outisde' library.

Is there a way in which we can achieve it.

Here is the link of my code: https://stackblitz.com/edit/angular-b61t71

Thank You.

Upvotes: 0

Views: 719

Answers (3)

ahmeticat
ahmeticat

Reputation: 1939

You can use HostListener and ViewChild like this

@ViewChild('tooltip') tooltip: ElementRef;

  @HostListener('document:click', ['$event'])
  clickout(event) {
    if (this.tooltip) {
      if (!this.tooltip.nativeElement.contains(event.target)) {
        this.clickHover = false;
      }
    }
  }

and update html file

<div #tooltip class="tooltip" (click)="clickHover = true">Click me!
  <span  [style.display]="clickHover ? 'block':'none'" class="tooltiptext">Tooltip text</span>
</div>

WORKING EXAMPLE

Upvotes: 2

Akif Hadziabdic
Akif Hadziabdic

Reputation: 2890

Bind event on a root element of your component or on document element or on the wrapper of your document and handle cases:

  1. click on your element
  2. click on other elements

Upvotes: 0

Emilien
Emilien

Reputation: 2761

Maybe you could add an overlay like this :

In .html :

<div class="overlay" *ngIf="clickHover" (click)="clickHover = false"></div>
<div class="tooltip" (click)="clickHover = true">Click me!
  <span *ngIf="clickHover" class="tooltiptext">Tooltip text</span>
</div>

in .css :

.overlay {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

Upvotes: 1

Related Questions