Rendering SVGs using Renderer2 in Angular

696 views Asked by At

How do I render an SVG (which I have locally stored in my project) using Renderer2 in Angular?

I tried doing it like following:

const div = this.renderer.createElement('div');
const svg = this.renderer.createText('<svg>{....}</svg>');
this.renderer.appendChild(div, svg);

But it actually got renderer as a text.

Can someone help?

2

There are 2 answers

0
Hsuan Lee On BEST ANSWER

The createText method is used to create a text node, in this case you can set innerHTML directly.

const div = this.renderer.createElement('div');
div.innerHTML = svgStr;
0
Eliseo On

Remember that you can create a svg with a selected path using a simple variable and [attr.d]="variable in a path, e.g.

<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 
      fill="currentColor" viewBox="0 0 16 16">
  <path [attr.d]="path"/>
</svg>

And in .ts:

path="M14 16a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12zM5.904 5.197 10 9.293V6.525a.5.5 0 0 1 1 0V10.5a.5.5 0 0 1-.5.5H6.525a.5.5 0 0 1 0-1h2.768L5.197 5.904a.5.5 0 0 1 .707-.707z"