Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 SVG not rendering

I created a component to render SVG images that are within my app.

The are loaded dynamically as the however, my demo app just show a simpler version.

http://plnkr.co/edit/g2tZXeUAMJ5zESx2EHT0?p=info

i tried <div [innerHTML]="data"></div> and <div> {{ data }} </div>

The SVG is not being loaded though the call is correct. I spent sometime in gitter to find a solution but the closest i got was it it's being sanitzed.

The innerHTML i assume is being sanitzed and the interpolation is being ignored. It just shows the raw svg text.

Thanks

like image 753
Nico Avatar asked Jul 09 '26 16:07

Nico


2 Answers

Angular is sanitizing the content. To work around explicitly tell Angular that it can trust your HTML

import { Pipe, Sanitizer } from '@angular/core';

You can use a reusable pipe or call sanitizer.bypassSecurityTrustHtml(html) directly.

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

@Pipe({ name: 'bypassHtmlSanitizer' })
export class BypassHtmlSanitizerPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

and use it like

[innerHTML]="data | bypassHtmlSanitizer"

Plunker example

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

like image 77
Günter Zöchbauer Avatar answered Jul 12 '26 08:07

Günter Zöchbauer


I would just like to add to Günter Zöchbauer's accepted answer, that in newer versions of Angular, we need to use DomSanitizer instead of Sanitizer, which can be imported using import { DomSanitizer } from '@angular/platform-browser';.

like image 28
Himanshu Patel Avatar answered Jul 12 '26 10:07

Himanshu Patel



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!