Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One click handler for multiple elements in Angular 2

Let's say we have a div with 3 links inside.

<div class="wrap">
    <a class="link">link1</a>
    <a class="link">link2</a>
    <a class="link">link3</a>
</div>

In order to assign a click handler for the links in jQuery we can do smth like this: $('.wrap a').on('click', callback);.

What is the best approach for that in Angular2?

From what I learned I could use a simple (click) for each link, like: <a class="link" (click)="callback()">, but to me it looks odd. Another option would be to use a directive and do smth like <a class="link" [directive]="value">, this one I like more.

Is there an even better implementation of described case?

like image 995
lesgrosman Avatar asked May 24 '17 22:05

lesgrosman


1 Answers

The click event will bubble up to the parent div so you could put a the event handler there.

  <div class="wrap" (click)="clicked($event)">
      <a id="link1" class="link">link1</a>
      <a id="link2" class="link">link2</a>
      <a id="link3" class="link">link3</a>
  </div>
  export class AppComponent {

    clicked(event: MouseEvent) {
      console.log(event.srcElement.id);
    }
  }
like image 129
JayChase Avatar answered Sep 17 '22 06:09

JayChase