I've been facing a challenge in my Angular application where I am trying to dynamically add paths to an SVG element within an HTML file. The issue is that even though the paths are getting added to the DOM, they are not showing up in the browser when rendered. Despite spending hours searching and experimenting, I haven't been able to pinpoint the problem. I have created a small demo app to replicate the issue, hoping that someone can help me identify what's going wrong.
Here is the Angular component template:
<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>
And here is the TypeScript code:
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)
}
}
When running the app, the predefined path in the template shows up correctly. However, upon clicking the button, a new path gets added as a child of the SVG element but fails to render in the browser.