Search code examples
angularangular2-templateangular2-components

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


Solution

  • 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