Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop mouse event propagation

People also ask

How do you prevent event propagation?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do I stop click event propagation?

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!

Which event can be used to stop event propagation in react?

14, returning false from an event handler will no longer stop event propagation. Instead, e. stopPropagation() or e. preventDefault() should be triggered manually, as appropriate.

How do you stop event propagation in typescript?

Try with (click)="$event. stopPropagation()" . It might help as it worked for me in my scenario.


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>

The simplest is to call stop propagation on an event handler. $event works the same in Angular 2, and contains the ongoing event (by it a mouse click, mouse event, etc.):

(click)="onEvent($event)"

on the event handler, we can there stop the propagation:

onEvent(event) {
   event.stopPropagation();
}

Calling stopPropagation on the event prevents propagation: 

(event)="doSomething($event); $event.stopPropagation()"

For preventDefault just return false

(event)="doSomething($event); false"

Event binding allows to execute multiple statements and expressions to be executed sequentially (separated by ; like in *.ts files.
The result of last expression will cause preventDefault to be called if falsy. So be cautious what the expression returns (even when there is only one)


Adding to the answer from @AndroidUniversity. In a single line you can write it like so:

<component (click)="$event.stopPropagation()"></component>

This worked for me:

mycomponent.component.ts:

action(event): void {
  event.stopPropagation();
}

mycomponent.component.html:

<button mat-icon-button (click)="action($event);false">Click me !<button/>

If you're in a method bound to an event, simply return false:

@Component({
  (...)
  template: `
    <a href="/test.html" (click)="doSomething()">Test</a>
  `
})
export class MyComp {
  doSomething() {
    (...)
    return false;
  }
}