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?

4 Answers 4

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);
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.