如何在angular(v4 +)上执行window.onclick() [英] how to perform window.onclick() on angular (v4+)

查看:58
本文介绍了如何在angular(v4 +)上执行window.onclick()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试关闭调用按钮(即窗口)外部的下拉单击.使用javascript就像我可以简单地

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');
    }
  }
 }
}

但是我猜打字稿不支持此操作,因为我在window.onclick [ts]';'上遇到错误.预期的.

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

还有其他可以对打字稿进行onClick检测而又不影响性能的方法

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

推荐答案

您可以在组件中使用类似这样的内容:

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';
    }
  }

这篇关于如何在angular(v4 +)上执行window.onclick()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆