Tomazbyden2000
Tomazbyden2000

Reputation: 103

Angular document.addEventListener listen to click outside

I have some code which listens to click inside and outside the element..

Here is the code on javascript.

document.addEventListener('click', (event) => {
 const isClickInside = this.nav.contains(event.target);
 if (!isClickInside) {
   if (this.dropdown.style.display === 'grid') {
     this.dropdown.style.display = 'none';
     this.button.innerHTML = 'menu';
    }
  }
});

This works when I put it in the ngOnInit ... but I would like to know how this could be done the angular way. I'm using Angular 11 btw.

How do I go about this?

Upvotes: 1

Views: 3322

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24462

you can use HostListener to create a handler for each click event inside component and outside

  @HostListener("click", ["$event"]) inClick(e: MouseEvent) {
    e.stopPropagation();
    this.clickStatus = "inside click";
  }

  @HostListener("document:click") outClickHandler() {
    this.clickStatus = "outside click";
  }

e.stopPropagation() prevent the click event inside the component from bubbling to parent elements , otherwise outClickHandler will be trigger

stopPropagation

stackblitz demo 🚀

another way by using just single method same as the your quetions

component

export class NavComponent {
  
  clickStatus = "";
    // 👇 ElementRef : a wrapper around a native element inside of a View.
  constructor(private el: ElementRef) {}

  @HostListener("document:click", ["$event"]) outClickHandler(e: MouseEvent) {
    if (this.el.nativeElement.contains(e.target)) {
      this.clickStatus = "inside click";
    } else {
      this.clickStatus = "outside click";
    }
  }

stackblitz demo 🌟🌟

Upvotes: 6

Related Questions