首页 > 解决方案 > HostListener OnClick 有时只工作

问题描述

在尝试在 Angular 中创建下拉框时,我遇到了一些不均匀的结果(我正在关注这些示例)。这是我的代码:

html

           ``` <button (click)="eqLocationDrop()" id="eqLocButton"><i class="fas fa-caret-down"></i> </button>
         <div id="eqLocDD" class="dropdown-content" *ngIf="showEQDD">
            <option *ngFor="let e of eqLoc" class="option" (click)="ddClick(e)">{{e.Loc}}
            </option>
          </div>```

ts

   if (event.target == document.getElementById("eqLocButton")) {

     console.log("button clicked");
   } else { //hide the drop down box, as a click has occurred outside the box
     this.showEQDD = false;
    console.log("button did NOT get clicked");
    }
   } 

 eqLocationDrop() { //show the drop down div
   this.showEQDD = true;
   }

 ddClick(e) {     // on click of an item in the drop down menu - get the data and hide the drop down
   console.log(e)
   this.showEQDD = false;

 }

对此进行测试,当我单击下拉按钮之外的任何位置时,我得到“未单击按钮”;但是,当单击下拉按钮时,它似乎会按预期随机工作,然后立即停止工作,没有明显的模式。当它运行正常时,它永远不会被关闭然后立即重新打开。我是否没有执行 if() 来检查按钮是否被正确单击?似乎 event.target 是随机变化的。

标签: htmlangulartypescript

解决方案


答案很简单——我尝试在控制台记录 event.target 对象,我了解到我有时会单击按钮,有时会单击按钮的图标。我曾认为该图标天生就是按钮的一部分,但显然它算作自己的对象,因此会使下拉菜单停止工作。我能够将一些文本放入此按钮并执行此操作:

html
<button id="eqButton" ><p id="v">V</p></button>

ts
    if(event.target == document.getElementById("eqButton") || event.target == document.getElementById("v")) {
    } else {
      this.showEDD = false;
    }

推荐阅读