W
W
worksss2017-10-17 14:15:53
Angular
worksss, 2017-10-17 14:15:53

How to dynamically insert svg in Angular2?

Good afternoon.
I would like to insert svg from the component (take it from the database)
https://plnkr.co/edit/lPAxCqhmHwBrotfw9Bgl?p=preview
Just substitution in the template works. And if to do through a variable that is not present. But it doesn't throw any error either. What to do? svg:path doesn't solve either
this.path = `<path d="m ....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sasha Novik, 2017-10-17
@worksss

Here you need to work directly with the DOM.
Create an SVG from a string:

private svgElementFromString(str: string): SVGElement {
  const div = document.createElement('div');
  div.innerHTML = str;
  const svg = div.querySelector('svg') as SVGElement;
  return svg;
}

And then we inject into the node:
const el = this.el.nativeElement;
el.innerHTML = '';
this.renderer.appendChild(el, svg);

There is also an option with [innerHTML]:
But you need to pass the line through the sanitizer:
constructor(private sanitizer: DomSanitizer)
  ...
  this.svg = this.sanitizer.bypassSecurityTrustHtml(svgString);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question