单击Angular 4应用程序中的SVG元素时调用函数

时间:2017-10-26 13:41:30

标签: javascript angular svg

我有一个带有SVG图像的角度4应用程序。 我想在点击SVG的一部分时调用一个函数。

这就是我展示svg的方式:

 <div class="svg" [innerHtml]="mySVG"> </div>

this.mySVG = this.sanitizer.bypassSecurityTrustHtml(containerSVGString);其中containerSVGString是SVG内容的字符串。

所以,如果在SVG中我有类似的东西:<g id="all" onclick="console.log('test')">它可以工作。

但如果我尝试用

<g id="all" onclick="myFunction()">
myFunction(){
    console.log('test);
}

在我的打字稿文件中声明,它不起作用。

在点击SVG元素时,你知道如何调用我的一个函数吗?

编辑: 我收到这个错误:

monitoring:1 Uncaught ReferenceError: myFunction is not defined
at SVGGElement.onclick 

1 个答案:

答案 0 :(得分:0)

下面是示例代码,单击下载svg图标,将调用组件方法downloadFile。

HTML :假设资产文件夹中有一个下载图标,还请确保添加指针事件:没有一个指针事件可确保单击事件被触发。

 <div class="icon-placeholder" (click)="downloadFile()">
          <object data="../../../assets/images/icon-download.svg" type="image/svg+xml"
            style="pointer-events: none;"></object>
          <span>Download</span>
        </div>

CSS :添加CSS

 .icon-placeholder {      
      font-size: 12px;
      display: flex;
      flex-direction: column;
      cursor: pointer !important ;
    }

ts 文件:

downloadFile(){
console.log('svg clicked');
}