matt helliwell
matt helliwell

Reputation: 2678

Dynamically updating SVG in Angular

I am trying to programatically add paths to an SVG element in an HTML in an Angular application. The problem is that the paths are being added to the DOM but are not rendering in the browser. Despite a day of searching and experimenting, I can't find what the issue is. I've reproduced the problem in a small app. Hopefully someone can spot what I'm doing wrong.

Angular template for the component:

<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 the Typescript:

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 you run the app, the hardcoded path in the template is displayed correctly. However when you click on the button, a path is inserted as child of the SVG element but the path isn't rendering in the browser.

Upvotes: 5

Views: 4756

Answers (1)

yurzui
yurzui

Reputation: 214037

Angular keeps namespaces map in its code:

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/',
};

which is used to create element with namespace:

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

So try using svg key as namespace:

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

Upvotes: 6

Related Questions