Darren Mitchinson
Darren Mitchinson

Reputation: 81

Rendering SVG data using Angular 2

I have an angular application that gets product information from a service and returns it in a json object. On the html template i want to display this SVG image on the page. I have tried a few different methods but I cant get any to render the image.

Method 1:

<div class="prodStruc" [innerHtml]="product?.StructureSVG" style="float:right">   

This method only renders the text from the svg image

Method 2:

<div class="prodStruc" style="float:right">            
      {{product?.StructureSVG}}
    </div>

This method spits out all the svg tags and data as a massive string (as expected)

Can anyone point me in the right direction on how to do this..if it can be done?

Upvotes: 3

Views: 1884

Answers (1)

Fabi
Fabi

Reputation: 85

I just had the same problem. This is the solution:

import {DomSanitizer, SafeHtml} from '@angular/platform-browser';

// inject DomSanitizer in constructor
private myImage: SafeHtml;

constructor(private sanitizer: DomSanitizer) {
  this.myImage = sanitizer.bypassSecurityTrustHtml(product.StructureSVG);
}
<div class="prodStruc" [innerHtml]="myImage"> </div>

And then in your template:

Upvotes: 5

Related Questions