Rem February 2016

Stop event propagation in Angular 2

What is the easiest way to stop mouse events propagation in Angular 2? 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.

Answers


Günter Zöchbauer February 2016

This should do:

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

(not tested)

For preventDefault just return false

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


Thierry Templier February 2016

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


jhadesdev February 2016

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();
}

Post Status

Asked in February 2016
Viewed 1,760 times
Voted 14
Answered 3 times

Search




Leave an answer