Code snippet
click-outside.directive.tsimport {
Directive,
ElementRef,
Output,
EventEmitter,
HostListener
} from "@angular/core";
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
@Output() clickOutside: EventEmitter<any> = new EventEmitter();
constructor(private elRef: ElementRef) { }
@HostListener("document:click", ["$event.target"])
onClick(target: any) {
if (!this.elRef.nativeElement.contains(target)) {
this.clickOutside.emit();
}
}
}
Using in HTML<div class="m-auto" style="width: 500px;">
<div><b>Clicked Outside </b> <span class="badge bg-secondary fs-4">{{clicked}}</span> times.</div>
<div class="badge bg-warning p-5 my-5" (clickOutside)="clickOutside()">
This is an element which attach clickOutside directive.
</div>
</div>
Using in TS fileimport { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-click-outside',
templateUrl: './click-outside.component.html',
styleUrls: ['./click-outside.component.scss']
})
export class ClickOutsideComponent implements OnInit {
opened: boolean = false;
clicked: number = 0;
constructor() { }
ngOnInit(): void {
}
clickOutside() {
this.clicked++;
}
}
Demo