在 Angular 中动态更新 SVG

mat*_*ell 5 javascript svg dom typescript angular

我正在尝试以编程方式在 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>
Run Code Online (Sandbox Code Playgroud)

和打字稿:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

yur*_*zui 6

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/',
};
Run Code Online (Sandbox Code Playgroud)

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

if (namespace) {
   return document.createElementNS(NAMESPACE_URIS[namespace], name);
}
Run Code Online (Sandbox Code Playgroud)

因此尝试使用svgkey 作为命名空间:

const path = this.renderer.createElement("path", 'svg')
                                                  ^^^^
Run Code Online (Sandbox Code Playgroud)