将在代码中创建(不是从服务器获取)的 SVG 附加到 angular 中的元素(避免获取 'unsafe')

Attach SVG that was created in code (not fetched from server) to an element in angular (avoid getting 'unsafe')

在我的 angular 10 应用程序中,我正在使用一个库 (svg.js) 在客户端中创建一个 svg(尽管我认为我的问题与我正在使用的库无关)。

    let svg = SVG().size(this.widthpx, this.heightpx).svg(); //returns an svg, 
    //although I treat it as any in typescript because I do not know any better

创建 svg 后,我想显示它。理想情况下作为 div 的背景图片,但我可以接受将其设置为 <img>.

的 src

我该怎么做? 我尝试使用此处描述的方式:

<div [style.background]="svg"></div>

我也尝试了以下方法,如这里所建议的:

<img id='other' [src]="svg">
<img id='other' src={{svg}}>

由于我对 typescript 和 angular 都是新手,我猜我这里有一个逻辑错误。我可能只是不能将一些类似 svg 的变量设置为 background/src,但需要以某种方式处理它?给它一个URI?将其转换为某种特定类型?

我知道,svgjs 库在其对象上有一个 attachTo() 方法。由于这种情况发生在 angular 之外,并且不允许我做任何我想做的事情,所以我想把事情掌握在自己手中。

我还可以再描述一些不起作用的地方。据我所知,使用 src={{svg}} or [src]="svg" almost 是可行的。但是 src 是“不安全的”。

<img _ngcontent-dgo-c96="" id="other" src="unsafe:<svg xmlns=&quot;http://www.w3.org/2000/svg&quot;(...shortended...) </svg>">

使用 [style.background] 方法会在错误的位置创建一个空的 svg 元素。

为此你需要

  1. 在上述div中定义一个Angular-reference(例如#svgContainer
  2. 通过 ViewChild
  3. 解决该引用
  4. 改变backgroundImage

我在这里提供了一个可行的解决方案(参见 app.component.tsapp.component.html:

https://codesandbox.io/s/sleepy-buck-r13ck?file=/src/app/app.component.ts