SVG in Angular 2
Adam Klein
Last updated on Mar 12, 2016

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 Home@1:26]

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

attr.X

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

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

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:

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

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

@Component({
    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>
</g>

In case you want to see it live: plunkr

Angular and MobX

Interested in seeing how to use Angular and MobX to build Tic-Tac-Toe? Click here for the full code and demo.

If you have any questions related to using SVG components in Angular, reach out. We as development consultants will field any of your questions with real-world experiences and no sales.

Back to all articles

© 500Tech. Building high-quality software since 2012.