Click Outside directive trong Angular

Click Outside directive trong Angular

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) { }

  // The second parameter ["$event.target"] is to define which values should be passed to the decoreated method
  // The $event parameter is a MouseEvent, which holds the target element in the target property
  // The onClick method will now be invoked every time a click was performed on the whole document.
  // Due to the use of HostListener, you don’t even need to unbind from the event—Angular is handling everything for you.
  @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

Live Demo

Đăng nhận xét

Mới hơn Cũ hơn