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

1 Comment

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(...)
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 Comment

jQuery seems to be a bit overkill for this use case ;-) jQuery should be avoided in Angular2 (if possible)

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.