Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
Darren Mitchinson Avatar asked Dec 12 '25 13:12

Darren Mitchinson


1 Answers

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:

like image 68
Fabi Avatar answered Dec 15 '25 10:12

Fabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!