Search code examples
javascripthtmlangularevent-propagation

How to prevent event bubbling in Angular 8?


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.


Solution

  • 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;
    }