4

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?

1
  • 1
    There is no angular code, can you show us what the part of your code that is based on angular so that someone could help you better. Commented Jun 22, 2016 at 22:01

2 Answers 2

7

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);
}
1
  • 5
    I think this is not the answer for the question. The question about binding click event based on the class. Something like what JQuery('.selectModal').click(...) Commented Aug 20, 2016 at 5:51
2

Yes, you can, but it depends on the strategy. You could do it by JQuery or using the DOM accessors. In my team we use JQuery but we don`t search the entire DOM to find the elements, instead, we use a class called ElementRef:

import { ElementRef } from '@angular/core';
...
constructor(private elementRef : ElementRef) {
}

ngAfterViewInit() {
    jQuery(this.elementRef.nativeElement).find('selectModal').on('click', () => {
    //do something here
    });
}

The ElementRef class is a reference for the component itself in the DOM. So we're able to filter the search to this component.

1
  • 7
    jQuery seems to be a bit overkill for this use case ;-) jQuery should be avoided in Angular2 (if possible) Commented Jun 23, 2016 at 6:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.