Reputation: 111
Please understand, I'm new in Angular and developing overall so this might be a very unexperienced problem.
The problem is that I am calling a function from a component's HTML template file with $event as an argument and it ends up capturing a different element from the one I wished to target. That exact element I am calling the event on has two children...
HTML:
<div class="cursorPointer" (click)="answeredQuestion($event)">
<div id="chickenTenders" class="backImageCov question_0Img"></div>
<h3 class="questionSubTitle">Chicken Tenders</h3>
</div>
I am aiming to retrieve the div container with "cursorPointer"
every single time I call this event. I hypothesize that it's an event bubbling problem because if I were to click on the div container with the id of "chickenTenders"
, that same container will be returned by the $event
argument in the answeredQuestion()
function on my ts file...
I have already searched online (Stop mouse event propagation) but in this example the student is asking a question that came from a directive so I got confused as to what the solution could be...
I have already tried:
(click)="answeredQuestion(0, $event);false"
And:
(click)="answeredQuestion(0, $event); $event.stopPropagation()"
However, none seem to help the cause. Putting it simply, I hope the solution would give me a simple way to get access to that parent element (<div class="cursorPointer">
) every single time, even if the child elements are the ones clicked.
Thank you for your time guys, I appreciate it.
Upvotes: 7
Views: 15045
Reputation: 140
You probably want to access currentTarget
:
answeredQuestion($event){
const cursorPointer = $event.currentTarget
// etc.
}
This gives you the element where the handler is attached. $event.target
gives you the element where the click occurred, in this case on of the children.
Upvotes: 0
Reputation: 97
You can handle the event propagation(bubbling) in angular.
Use this in your child component.
onClick(event: Event) {
event.stopPropagation();
// do your stuff
}
Upvotes: 8
Reputation: 2007
You can use a template reference variable to grab a reference to your desired element.
<div #clickElement class="cursorPointer" (click)="answeredQuestion(clickElement)">
Upvotes: 1
Reputation: 2799
What if you disabled the pointer events for the child elements with CSS?
.cursorPointer > div, .cursorPointer > h3{
pointer-events: none;
}
Or better:
.cursorPointer > * {
pointer-events:none;
}
Upvotes: 2