Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind click event by class in Angular 2

Let's say I have the following template:

<ul>
 <li id="1" class="selectModal">First</li>
 <li id="2" class="selectModal">Second</li>
 <li id="2" class="selectModal">Third</li>
</ul>

How can I bind a click event by class in TypeScript, so when a li element is clicked I can get the element and query the ID or any other attribute of the clicked element?

like image 246
Ultranuke Avatar asked Jan 06 '23 20:01

Ultranuke


1 Answers

There are many ways to do that. Straight forward solution:

<ul (click)="onClick($event.target)">
 <li id="1" class="selectModal">First</li>
 <li id="2" class="selectModal">Second</li>
 <li id="2" class="selectModal">Third</li>
</ul>

onClick(e:HTMLElement){
    console.log(e.id, e.className);
}
like image 182
kemsky Avatar answered Jan 15 '23 13:01

kemsky