Blog>
Snippets

Listening to Element Events

Explain how to use Renderer2 to listen for click events on a button and handle them in Angular.
import { Component, Renderer2, ElementRef, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `<button #myButton>Click me!</button>`
})
export class MyComponent implements OnInit {

  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngOnInit() {
    // Obtaining a reference to the native element
    const button = this.el.nativeElement.querySelector('button');

    // Listening for click events on the button
    const unlisten = this.renderer.listen(button, 'click', (event) => {
      this.handleClick(event);
    });

    // If you ever want to remove the listener
    // unlisten();
  }

  handleClick(event: Event) {
    // Handle the click event
    console.log('Button clicked!', event);
  }

}
This code snippet defines an Angular component with a button element in its template. The `ngOnInit` lifecycle hook obtains a reference to the button and uses `Renderer2` to listen for click events. When a click event occurs, the `handleClick` method is called, and the event is logged to the console. The `unlisten` function is a callback that can be called to remove the event listener if needed.