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