Kamczatka
Kamczatka

Reputation: 161

Angular2 events delegate

in clear Javascript i can delegate events, to decrease number of necessary functions handling events to one, for the entire node set. For example:

<div id="click-wrap">
  <button>Click me, nr 1</button>
  <button>Click me, nr 2</button>
  <button>Click me, nr 3</button>
</div>

How to get similar effect in angular2? In detail I want to remove add class

Upvotes: 1

Views: 2143

Answers (2)

Arjun Yelamanchili
Arjun Yelamanchili

Reputation: 587

From LearnAngular2.com

@Component(...)
class MyComponent {
  clicked(event) {
    // This gives you the event object
    // You can do things like any normal event such as view the target
    console.log(event.target);
  }
}
<div id="click-wrap" (click)="clicked($event)">
  <button>Click me, nr 1</button>
  <button>Click me, nr 2</button>
  <button>Click me, nr 3</button>
</div>

Upvotes: 0

Max Koretskyi
Max Koretskyi

Reputation: 105439

Just add a directive to the <div id="click-wrap"> that will bind to the click event and read event.target:

@Directive({selector: '[custom]')
export class CustomDirective {
   @HostListener('click') clicked($event) {
      console.log($event.target); // this will be a child button
   }
}

<div id="click-wrap" custom>

Upvotes: 1

Related Questions