Search code examples
angulardom-eventsevent-propagation

Stop mouse event propagation


What is the easiest way to stop mouse events propagation in Angular ?

Should I pass special $event object and call stopPropagation() myself or there is some other way.

For example in Meteor, I can simply return false from event handler.


Solution

  • If you want to be able to add this to any elements without having to copy/paste the same code over and over again, you can make a directive to do this. It is as simple as below:

    import {Directive, HostListener} from "@angular/core";
        
    @Directive({
        selector: "[click-stop-propagation]"
    })
    export class ClickStopPropagation
    {
        @HostListener("click", ["$event"])
        public onClick(event: any): void
        {
            event.stopPropagation();
        }
    }
    

    Then just add it to the element you want it on:

    <div click-stop-propagation>Stop Propagation</div>