首页 > 解决方案 > 在 Angular 中捕获 SVG 内的类的点击事件

问题描述

在我的 Angular 9 应用程序中,我需要将 svg 文件添加为交互式图像。

svg 本身在my-file.svg其中,如下所示:

<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>

我有一个组件:

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

    elementClicked() {
    }
}

car-view.component.html我将这个 svg 包括为:

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

如何在点击事件(在 svg 内部)上调用elementClicked()内部函数?我还需要切换另一个类(例如)以将 svg 多边形标记为已单击。CarViewComponentmy-polygon-classelement-clicked

标签: javascripthtmlangularsvg

解决方案


以这种方式添加

<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>

推荐阅读