link1

One click handler for multiple elements in Angular 2

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>

To assign a click handler for the link in jQuery, we can do so: $('.wrap a').on('click', callback);.

What is the best approach for this in Angular2?

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

Is there an even more efficient implementation of the described case?

+4
source share
4 answers

div, .

  <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);
    }
  }
+1

, . clickHandler, (). ?

ClickEvent , $event : <a class="link" (click)="callback($event)">link</a>

, :

public links = ['link1','link2','link3'];

:

<div class="wrap">
    <a class="link" *ngFor="let link of links">{{link}}</a>
</div>

SinglePageApplication, routerLink.

<a routerLink="/my-path">link1</a>
+2
@Component({
  selector: 'my-app',
  template: `
    <div>
      <div (click)="onClick($event)">
        <a id="link1" href="#" class="link">link1</a>
        <a id="link2" href="#" class="link">link2</a>
        <a id="link3" href="#" class="link">link3</a>
      </div>
    </div>
  `,
})
export class App {
  constructor() {
  }
  onClick(event) {
      alert(event.srcElement.id);
  }
}

Plunkr

+1

, - , , HTML, ,

0

Source: https://habr.com/ru/post/1677880/


All Articles