Main

Angular Event Binding: How to Add an Event Listener to a DOM Element at Runtime?

GET my Web Performance course for FREE till November 13, 2023: https://www.udemy.com/course/identify-and-fix-javascript-memory-leaks/?couponCode=2041407C7E77E9F1B9E1 Join 30K+ students and check my Udemy video course: Web Performance 101: Your Guide to Boost Your Web Apps: https://www.udemy.com/course/identify-and-fix-javascript-memory-leaks Angular: A Tough Climb Worth the View: https://medium.com/gitconnected/angular-power-vs-react-778e09647651 Inside the Angular Universe: A Q&A Journey: https://levelup.gitconnected.com/angular-q-and-a-guide-f92471ed3d2c Angular Performance: 5 OnPush Change Detection Case Studies: https://betterprogramming.pub/angular-onpush-change-detection-f629cbce0bfa 💡 🧠 I write about engineering, technology, and leadership for a community of smart, curious people. Join my free email newsletter for exclusive access: https://rakiabensassi.substack.com You can also find more of my articles here: https://rakiabensassi.medium.com

TekForge | Rakia Ben Sassi

7 months ago

Have you ever wondered how to add an event  listener to a DOM element in Angular at runtime? In Angular, you typically bind to events using the  event binding syntax in your templates. However, if you want to add an event listener at runtime,  you can use the Renderer2 class, which provides an API that can safely be used even when direct  access to native elements is not supported. Let's see an example of this. In this source code, we're looping through a list of fields, and for each one of them
,  we're adding a stylesheet by calling .addClass() method from Renderer2. Now I want to add a  click event listener and not just stylesheet. To achieve this, I will call this.render.listen()  to my span element and I need to specify my event which is 'click' in this case. Then  here is the logic that I want to run when a click event happens. As a logic,  I have for the moment just console.log(). So in this example, Renderer2's listen method  is used to add a click event listener to a DOM elemen
t. When the element is clicked, a  message will be logged to the console. Just remember to clean up (unsubscribe) the  event listener in the ngOnDestroy lifecycle hook to prevent memory leaks if the component is  destroyed. The listen function returns a callback that, when called, will remove the event listener. This way you can dynamically  add event listeners in Angular. However, in general, it's recommended  to use angular's template syntax for event binding whenever possible. As it  integrat
es better with angular's change detection system and is generally easier to manage. So I hope that was helpful. If you enjoyed the video, don't forget to hit the like button and  subscribe to the channel. And see you next time!

Comments