[英]Dynamically updating SVG in 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>
和打字稿:
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元素的子級插入,但該路徑不會在瀏覽器中呈現。
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')
^^^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.