Angular - How to bind a event to HTML elements by selector?

Viewed 272

I would like to bind a same event to all HTML elements that contains a specific class in a component

Example:

<span class="myClass">Item1</span>
<span class="myClass">Item2</span>
<span class="myClass">Item3</span>

What I would like to do in Angular 8+:

document.querySelectorAll(".myClass").forEach(item => item.addEventListener('click', event => myFunction(event));

Is this even possible with Angular?

I did some searches but I didn't find what I really need.

I need to do this inside a MatTable ng-containers that contains a <span contentEditable=true></span>

1 Answers

If the elements will all share a common set of requirements (a certain class and listener), you could create a directive that encapsulates these and add that directive to the elements directly. Here's a good article on Directive selector types (section 3 is about class selectors)

Regarding doing this automatically with a selector.... you're also trying to target elements that are in a MatTable <span contenteditable..>. I'm pretty sure that selectors in Angular directives cannot cross element boundaries e.g. cannot target child elements of a particular matching element. You may need to go with your querySelectorAll approach on this one

Although it's considered bad practice to revert to using querySelector in Angular, the Angular team do it themselves when needs be:

Note: when you try to remove the components that have the listeners attached, they may linger in memory if the component with the event handlers is still around - so remove the listeners if that's the case.... or not

Related