0

I have this html element on my application:

.html

<a (click)="onOpen($event)">
    <i class="fa fa-file-text-o"></i> 
    <p>Profile</p>
</a>

.ts

onOpen(event):void {
    console.log( event.target );
}

When I click on the element I get different results for event.target inside the function onOpen() dependening on the position I click on.

For example, if I click ont he element where there is the p text, the target is going to be the p element instead of the a element.

Is there a way to make it always be the element that has the click function?

celsomtrindade
  • 4,501
  • 18
  • 61
  • 116
  • https://stackoverflow.com/questions/46987482/angular-anchor-tag-clicked-element-id-not-showing/46987777#46987777 – yurzui Nov 18 '17 at 15:59

4 Answers4

2

Use event.currentTarget to get the element the listener is bound to

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

event.currentTarget is what you are looking for

onOpen(event:Event):void {
    console.log( event.currentTarget );
}
br.julien
  • 3,420
  • 2
  • 23
  • 44
0

Angular return the true target because you actually click the p not a.The p is contain a with one hundred percentage width to cover.

One way to solve it , use $event.currentTarget to got origin target.

Rach Chen
  • 1,322
  • 2
  • 10
  • 26
0

You could pass a string or object in the (click) and play around with that instead trying to manipulate the DOM

For example:

in the .html onOpen($event, 'profile') or onOpen($event, menu.profile)

in the .ts file

public menu: = { profile: {name: 'Profile', url: '....', icon: 'sample.svg', isActive: true }, home: {...} }

Are you trying to add an active class in the menu item or what exactly are you trying to achieve ?

EDIT:

<a (click)="onOpen($event, menu.profile)" [class.active]="menu.profile.isActive === true"> <i class="fa fa-file-text-o"></i> <p>Profile</p> </a>

DrNio
  • 1,936
  • 1
  • 19
  • 25
  • This is for other things. I really need the dom element to do some calculations and change the style of others (parent child elements). If it was just for classes, I could use routerLinkActive to activate the element. – celsomtrindade Nov 18 '17 at 18:10