1

I add some HTML to the DOM dynamically. There are several hyperlinks with class someClass and different ids. And after I add them to template I add event listener to them so when I click them id is logging.

this.HTMLdiv = this.domSanitizer.bypassSecurityTrustHtml(this.HtmlString);
this.changeDetectorRef.detectChanges();
this.elementRef.nativeElement.querySelector('.someClass').addEventListener('click', (e) => console.log(e.path[1].id));

Problem is that this event listener is added only to first element. How can I add it to all elements with class someClass?

1 Answer 1

2

You could use the querySelectorAll() function. Try the following

this.HTMLdiv = this.domSanitizer.bypassSecurityTrustHtml(this.HtmlString);
this.changeDetectorRef.detectChanges();
const elements = this.elementRef.nativeElement.querySelectorAll('.someClass');
elements.forEach((element) => element.addEventListener('click', (e) => console.log(e.path[1].id)));
Sign up to request clarification or add additional context in comments.

1 Comment

That's the injected ElementRef. I've modified the answer.

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.