Angular 2 - 单击父元素时阻止单击子项?

时间:2017-08-01 06:02:59

标签: angular typescript

当我点击锚标签onClick函数被调用但其子元素onclick函数也被调用。如果单击父元素然后单击其子元素的原因,我想阻止它。

以下是代码:

<li *ngFor = "let category of categories">
      <a href="javascript:void(0);"  (click)="toggle($event);">
        <span class="ah-pull-left" style="padding: 7px 10px;font-size: 14px;">
            <span class="ah-hexa">C</span>
        </span>
        <span class="ah-pull-left">{{category.title}}</span>
        <span class="ah-pull-right ah-sidebar-down-arrow" *ngIf = "category.submenu.length > 0"><i class="fa fa-angle-down" aria-hidden="true"></i></span>
      </a>
      <div id="{{category.id}}" class="ah-sidebar-sub-menu" *ngIf = "category.submenu">
          <ul>
              <li *ngFor = "let subcategory of category.submenu">
                  <a href="{{subcategory.link}}">
                    <span class="ah-pull-left" style="font-size: 14px;">
                        <span class="ah-hexa">{{subcategory.title.charAt(0)}}</span>
                    </span>
                    <span class="ah-pull-left">{{subcategory.title}}</span>
                    </a>
              </li>
          </ul>
      </div>
    </li>

.TS

toggle(e) {
    if(e.target || e.srcElement || e.currentTarget){
        console.log(e.target.parentNode)
    }
}

浏览器控制台窗口中的输出:

enter image description here

2 个答案:

答案 0 :(得分:2)

也许您可以像这样将源元素发送到onClickHandler。

function onClickA(event, element) {
  console.log(event, element);
  event.preventDefault();
}
<a onclick="onClickA(event, this)">
  <span>Hello</span>
  <span>World</span>
</a>

答案 1 :(得分:1)

<强>答案

在我的情况下,代码有效:

<a #myElement href="javascript:void(0);" id="{{category.id}}" (click)="onClick(myElement.id);">

但我不知道#myElement如何阻止点击子元素。顺便说一句,这工作正常,我得到了我点击的实际元素。

这是我的.html代码:

<li *ngFor = "let category of categories">
      <a #myElement href="javascript:void(0);" id="{{category.id}}" (click)="onClick(myElement.id);">
        <span class="ah-pull-left" style="padding: 7px 10px;font-size: 14px;">
            <span class="ah-hexa">C</span>
        </span>
        <span class="ah-pull-left">{{category.title}}</span>
        <span class="ah-pull-right ah-sidebar-down-arrow" *ngIf = "category.submenu.length > 0"><i class="fa fa-angle-down" aria-hidden="true"></i></span>
      </a>
      <div  class="ah-sidebar-sub-menu" *ngIf = "category.submenu" style="display: none">
          <ul>
              <li *ngFor = "let subcategory of category.submenu">
                  <a href="{{subcategory.link}}">
                    <span class="ah-pull-left" style="font-size: 14px;">
                        <span class="ah-hexa">{{subcategory.title.charAt(0)}}</span>
                    </span>
                    <span class="ah-pull-left">{{subcategory.title}}</span>
                    </a>
              </li>
          </ul>
      </div>
    </li>

这是我的.ts代码:

onClick(e) {
    console.log('HTML Element ID: ' + e);
}