Issue
When I clicked on anchor tag onClick
function is called but its child elements onclick function also called with it. I want to prevent this if parent element is clicked then why its child elements clicked with it.
Here is the code:
<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)
}
}
Output in browser console window:
Solution
Answer:
In my case below code works:
<a #myElement href="javascript:void(0);" id="{{category.id}}" (click)="onClick(myElement.id);">
But I don’t know how #myElement
is preventing child elements to be clicked. BTW this is working fine and I’m getting the actual element on which I had clicked.
Here is my .html code:
<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>
Here is my .ts code:
onClick(e) {
console.log('HTML Element ID: ' + e);
}
Answered By – Ahmer Ali Ahsan
Answer Checked By – Gilberto Lyons (BugsFixing Admin)