Blog>
Snippets

Binding to SVG Events with Angular

Show how to listen for and respond to user-initiated SVG events, such as click or hover, in Angular templates by using event binding syntax to call component methods.
import { Component } from '@angular/core';

@Component({
  selector: 'app-svg-component',
  template: `
    <svg width="100" height="100">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"
        (click)="onCircleClick($event)"
        (mouseover)="onCircleMouseOver($event)"
        (mouseout)="onCircleMouseOut($event)">
      </circle>
    </svg>
  `,
  styles: []
})
export class SvgComponent {
  onCircleClick(event: MouseEvent): void {
    console.log('Circle was clicked!', event);
  }

  onCircleMouseOver(event: MouseEvent): void {
    console.log('Mouse is over the circle!', event);
  }

  onCircleMouseOut(event: MouseEvent): void {
    console.log('Mouse is out of the circle!', event);
  }
}
This Angular component 'SvgComponent' defines an SVG circle within its template and listens for click, mouseover, and mouseout events. The event handlers onCircleClick, onCircleMouseOver, and onCircleMouseOut are bound to these events respectively using Angular's event binding syntax (event). The methods are implemented to simply log that the event occurred, along with the event object information.