Detect click outside Angular component
How can I detect clicks outside a component in Angular?
Answers
import { Component, ElementRef, HostListener, Input } from '@angular/core'; @Component({ selector: 'selector', template: ` <div> {{text}} </div> ` }) export class AnotherComponent { public text: String; @HostListener('document:click', ['$event']) clickout(event) { if(this.eRef.nativeElement.contains(event.target)) { this.text = "clicked inside"; } else { this.text = "clicked outside"; } } constructor(private eRef: ElementRef) { this.text = 'no clicks yet'; } }
A working example - click here
An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.
http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview
private wasInside = false; @HostListener('click') clickInside() { this.text = "clicked inside"; this.wasInside = true; } @HostListener('document:click') clickout() { if (!this.wasInside) { this.text = "clicked outside"; } this.wasInside = false; }
Above mentioned answers are correct but what if you are doing a heavy process after losing the focus from the relevant component. For that, I came with a solution with two flags where the focus out event process will only take place when losing the focus from relevant component only.
isFocusInsideComponent = false; isComponentClicked = false; @HostListener('click') clickInside() { this.isFocusInsideComponent = true; this.isComponentClicked = true; } @HostListener('document:click') clickout() { if (!this.isFocusInsideComponent && this.isComponentClicked) { // do the heavy process this.isComponentClicked = false; } this.isFocusInsideComponent = false; }
Hope this will help you. Correct me If have missed anything.
You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package