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.
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;
}
You can handle the event propagation(bubbling) in angular.
Use this in your child component.
onClick(event: Event) {
event.stopPropagation();
// do your stuff
}
您可以使用模板引用变量来获取对所需元素的引用。
<div #clickElement class="cursorPointer" (click)="answeredQuestion(clickElement)">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.