SVG in Angular 2

Adam Klein

If you just tried using SVG naively in Angular2, you will get weird errors, such as:

main.bundle.js:27686 EXCEPTION: TypeError: Cannot set property r of #<SVGCircleElement> which has only a getter in [radius in [email protected]:26]

Here are a few tips for building SVG components in Angular2.


In order to bind to SVG element attributes In angular 2, you must prefix them with attr., e. g.:

  <circle [attr.r]="myRadius" cx="50" cy="50"></circle>  

svg: prefix

Angular needs to know whether the component’s namespace is HTML or SVG. If the first tag of the component’s template is svg, angular guesses the SVG namespace.

If you want to make inner SVG components that don’t have the SVG tag, you must prefix them with ‘svg:’.

<svg:circle [attr.r]="myRadius" cx="50" cy="50"></svg:circle>

[attribute] selector

SVG is very strict and cannot accept elements it doesn’t know. For example, this is invalid markup:

  <myCircle> <!-- INVALID! -->
    <circle r="40" cx="50" cy="50"></circle>

So, to make inner components of SVG you must use an [attribute] selector:

    selector: '[myCircle]',
    template: '<svg:circle [attr.r]="myRadius" cx="50" cy="50"></svg:circle>'

And use it as an attribute (usually on svg or g elements):

<g myCircle></g>
The result HTML would look something like:

<g myCircle>  
  <circle r="40" cx="50" cy="50"></circle>

In case you want to see it live: plunkr