zken
zken

Reputation: 1036

Dynamic SVG Component

I would like to implement a component that dynamicaly bind a svg file, and load his content in the component template.

Currently, I tried this way :

icon.component.ts

...

@Component({
    selector: 'app-icon',
    template: `
        <div [innerHTML]="svgTemplate">
        </div>
    `,
})
export class IconComponent implements OnInit {
    @Input() name: string;

    private svgTemplate: string;

    constructor(
        private http: Http
    ) { }

    ngOnInit() {
        this.http.get(`assets/icon/ic_${this.name}.svg`).map(response => response.text()).subscribe(svg => {
            this.svgTemplate = svg;
        });
    }
}

But the svg content seems to be escaped (nothing appear in the template div).

Here is a content svg example :

<svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 52.4 44.1" style="enable-background:new 0 0 52.4 44.1;" xml:space="preserve">
<style type="text/css">
    .st0{fill:#444444;}
</style>
<g>
    <g transform="translate(312, 312)">
        <path class="st0" d="M-259.6-312H-312v6.4h52.4V-312z"/>
    </g>
    <g transform="translate(312, 312)">
        <path class="st0" d="M-259.6-293.1H-312v6.4h52.4V-293.1z"/>
    </g>
    <g transform="translate(312, 312)">
        <path class="st0" d="M-259.6-274.3H-312v6.4h52.4V-274.3z"/>
    </g>
</g>
</svg>

Upvotes: 2

Views: 2462

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

Angular automatically sanitizes HTML based on its security rules if the source is potentially untrusted. A lot of the SVG is probably being sanitized including the style rules.

If you trust the source of the svg you can bypass this using DomSanitizer. Note that this makes you potentially vulnerable to injection attacks, but since you control the server that is serving the svg it's a little less risk than if it were being retrieved from a source you did not control. This doesn't mean there is no risk, however.

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

this.svgTemplate = this.domSanitizer.bypassSecurityTrustHtml(svg);

Upvotes: 4

Related Questions