首页 > 解决方案 > 在 Angular 中动态更新 SVG

问题描述

我正在尝试以编程方式在 Angular 应用程序的 HTML 中添加 SVG 元素的路径。问题是路径被添加到 DOM 中,但没有在浏览器中呈现。尽管进行了一天的搜索和试验,但我找不到问题所在。我已经在一个小应用程序中重现了这个问题。希望有人能发现我做错了什么。

组件的角度模板:

<div style="text-align:center">
  Click the button to add a path to the svg
  <button (click)="onClickMe()">Click me!</button>
</div>
<div>
  <svg #svg
       xmlns="http://www.w3.org/2000/svg"
       width="200mm"
       height="200mm"
       viewBox="0 0 200 200">
    <path
      style="fill:#000000;fill-opacity:1;stroke:#000000;"
      d="M 60,147 h 40 v 30 H 85 V 157 H 75 v 20 H 60 Z"
      id="path1">
    </path>
  </svg>
</div>

和打字稿:

import {Component, ElementRef, Renderer2, ViewChild} from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('svg') svg: ElementRef

  constructor(private renderer: Renderer2) {
  }

  onClickMe() {
    const path = this.renderer.createElement("path", 'http://www.w3.org/2000/svg')
    this.renderer.setAttribute(path, "d", 'M60,150 H50 V 50 Z')
    this.renderer.setAttribute(path, "style", "fill:#F00;")

    this.renderer.appendChild(this.svg.nativeElement, path)
  }
}

运行应用程序时,模板中的硬编码路径会正确显示。但是,当您单击该按钮时,会插入一个路径作为 SVG 元素的子元素,但该路径不会在浏览器中呈现。

标签: javascriptangulartypescriptdomsvg

解决方案


Angular 在其代码中保留命名空间映射:

export const NAMESPACE_URIS: {[ns: string]: string} = {
  'svg': 'http://www.w3.org/2000/svg',
  'xhtml': 'http://www.w3.org/1999/xhtml',
  'xlink': 'http://www.w3.org/1999/xlink',
  'xml': 'http://www.w3.org/XML/1998/namespace',
  'xmlns': 'http://www.w3.org/2000/xmlns/',
};

用于创建具有命名空间的元素

if (namespace) {
   return document.createElementNS(NAMESPACE_URIS[namespace], name);
}

所以尝试使用svg键作为命名空间:

const path = this.renderer.createElement("path", 'svg')
                                                  ^^^^

推荐阅读