Search code examples
angularsvgdynamic

Passing svg to an angular component as a prop


I am trying to create a dynamic toolbox component, and I want to have the svg for the image to be drawn on each tile of the toolbox to be drawn from this svg string I pass to the toolbox tile compomnent.

<toolbox>
<tile myprop='<rect width="20" height="20" y="7" x="7" stroke="#FFF" stroke-width="2" fill="none" />' />
</toolbox>

My tile component template could look something like this

<div>
<svg>
{{myprop}}
</svg>
</div>

This won't work I know because of sanitizers, but I am relatively new to Angular and could not see a way to access the @Input prop in the component contstructor to use the sanitizer to trust the content.

What is the best way of rendering dynamic content from a string, safely, in an angular component such that I can keep the svg logic outside of the component templates and load it at runtime from perhaps a JSON file?


Solution

  • DomSanitizer.bypassSecurityTrustHtml return a "SafeHtml"

    So you need binding to [innerHTML]

    //your title component.html
    <div>
      <svg [innerHTML]="myprop">
      </svg>
    </div>
    

    In the input use a "setter"

    export class AppTile {
      myprop!: SafeHtml; //you can use also "any"
      @Input('myprop') set _(value: string) {
        this.myprop = this.sanitizer.bypassSecurityTrustHtml(value);
      }
      constructor(private sanitizer: DomSanitizer) {}
    }
    

    a stackblitz (NOTE I use stroke="red", because "#FFF" is white)