6

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.

Alek Carvajal
  • 101
  • 1
  • 2
  • 6
  • Why do you first have a call of `answeredQuestion` with one argument, and then with two? – trincot Jan 30 '20 at 19:56
  • Well, it has barely to do with the whole point of the question. However, it was an editing error in stack overflow. I had to edit my code a lot more in order to simplify it and make the main question a whole lot more understandable. There where unnecessary bits of code. Think of it as if it only had one parameter originally... ($event reference.) Thank you for your comment BTW – Alek Carvajal Jan 30 '20 at 22:32

3 Answers3

6

You can handle the event propagation(bubbling) in angular.

Use this in your child component.

onClick(event: Event) {
    event.stopPropagation();
    // do your stuff
  }
Pratul Dubey
  • 77
  • 1
  • 3
2

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;
}
A.Sharma
  • 2,771
  • 1
  • 11
  • 24
1

You can use a template reference variable to grab a reference to your desired element.

<div #clickElement class="cursorPointer" (click)="answeredQuestion(clickElement)">
Alex K
  • 1,937
  • 11
  • 12