Skip to content
Advertisement

Catch the click event on class inside SVG in Angular

In my Angular 9 app I need to add the svg file as an interactive image.

The svg itself is in my-file.svg and looks like this:

<svg>
    <polygon class="my-polygon-class" points="31.7793,138.705 39.7885,138.705 39.7885,128.848 31.7793,128.848 "/>
    <!-- lots of other polygons and paths -->
</svg>

I have a component:

@Component({
  selector: 'car-view',
  templateUrl: './car-view.component.html',
  styleUrls: ['./car-view.component.scss']
})
export class CarViewComponent {
    constructor() {
    }

    elementClicked() {
    }
}

And in the car-view.component.html I include this svg as:

<div class="car-view">
    <object data="../assets/my-file.svg" type="image/svg+xml"></object>
</div>

How can I call the elementClicked() function inside CarViewComponent on click event on my-polygon-class (which is inside the svg)? I also need to toggle another class (say element-clicked) in order to mark the svg polygon as clicked.

Advertisement

Answer

add it in this way

<div (click)='elementClicked()'>
<svg>
    <polygon class="my-polygon-class" points="31.7793,138.705 39.7885,138.705 39.7885,128.848 31.7793,128.848 "/>
    <!-- lots of other polygons and paths -->
</svg>
</div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement