Search code examples
angularsvgangular-directive

How to add SVGelement with Angular TypeScript


I have an Angular service which returns SVGElements, and I'd like to include them in a template, but I'm having trouble inserting them into the template. I'm sure this is a common thing to do but all my Googling and RTFM'ing, has failed me.

Here's a minimal example (after calling ng init, of course):

[app.component.html]
<h1>
  {{title}}
  <div [innerHTML]="circle"></div>
  <div [innerHTML]=circle.outerHTML></div>
  <div >{{circle}}</div>
  <div >{{circle.outerHTML}}</div>
</h1>

,

[app.componoent.ts]
import { Component } from '@angular/core';

// create an SVGElement
var svg_string  = '<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg>'
var parser = new DOMParser();
var circle_elt = parser.parseFromString(svg_string, "image/svg+xml").childNodes[0];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  circle = circle_elt;
}

And what I get is a web page that displays the text:

app works!
[object SVGSVGElement]
[object SVGSVGElement]
<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"/> </svg>

and in the console, there are messages stating:

"WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss)."


Solution

  • You need to apply the sanitizer:

    constructor(private sanitizer:DomSanitizer){}
    
    var circle_elt = this.sanitizer.bypassSecurityTrustHtml(
        parser.parseFromString(svg_string, "image/svg+xml").childNodes[0]
    );
    

    See also In RC.1 some styles can't be added using binding syntax