Ronit Oommen
Ronit Oommen

Reputation: 3160

how to perform window.onclick() on angular (v4+)

I have been trying to close a drop-down on-click outside of the invoking button(ie. window). Using javascript it was easy as i could simply

  // Close the dropdown menu if the user clicks outside of it
window.onclick = function (event) {
if (!event.target.matches('.bulk-dropbtn')) {

  var dropdowns = document.getElementsByClassName("bulk-dropdown-content");
  var i;
  for (i = 0; i < dropdowns.length; i++) {
    var openDropdown = dropdowns[i];
    if (openDropdown.classList.contains('show')) {
      openDropdown.classList.remove('show');
    }
  }
 }
}

But I guess typescript doesn't support this, as I am getting an error on window.onclick [ts] ';' expected.

Is there any other method I can perform an onClick detection on typescript without compromising on performance

Upvotes: 2

Views: 7155

Answers (2)

Lucas Rosello
Lucas Rosello

Reputation: 11

Try this:

@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent) {
    if (!(event.target == document.getElementById("THE ID OF YOUR BUTTON"))) {
      var dropdowns = document.getElementsByClassName("dropdown-content");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
        }
      }
    }
  }

Upvotes: 1

tlt
tlt

Reputation: 15211

You can use something like this within your component:

  @HostListener('document:click', ['$event'])
  onDocumentClick(event: MouseEvent) {
    const dropDownParent = checkIfYourTargetIsWithinSomeParentFunction(event.target, 'toolbar');
    if (!dropDownParent && this.dropdownElementRef) {
      //if its not within given parent > hide it this way or set boolean
      //variable that's bound to elements visibility property in template
      this.dropdownElementRef.style.display = 'none';
    }
  }

Upvotes: 5

Related Questions