5

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?

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
lesgrosman
  • 53
  • 5

4 Answers4

3

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);
    }
  }
JayChase
  • 11,174
  • 2
  • 43
  • 52
2

Actually it depends on what you would like to do. But if you just want to assign a clickHandler you normaly go with the (click) directive. Why does this looks odd to you?

If you would like to access the ClickEvent within you handler pass the $event paramter to your callback like so: <a class="link" (click)="callback($event)">link</a>

if you have a collection of links you can iterate over it:

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

then in your template:

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

If you just want to navigate within your singlePageApplication you usually just use the routerLink directive.

<a routerLink="/my-path">link1</a>
ShabbY
  • 896
  • 5
  • 9
1
@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);
  }
}

Working Plunkr

The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
0

In my opinion the best way for this is to use directive and maybe parse the inner HTML to compose a valid link as described in here

Jakub Licznerski
  • 1,008
  • 1
  • 17
  • 33