Reputation: 750
In my angular 10 app, I am using a library (svg.js) to create an svg in the client (although I think my question is independent from what library I am using).
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
Once that svg is created I would like to display it. Ideally as the background image of a div, but I can live with setting it as src of an <img>
.
How do I do this? I tried using the way described here:Angular dynamic background images
<div [style.background]="svg"></div>
I also tried the following ways, as suggested here: Change img [src] dynamically
<img id='other' [src]="svg">
<img id='other' src={{svg}}>
As I am new to both typescript and angular, my guess is, there is a logical error here on my part. I probably just cannot set some svg-like-variable as background/src, but need to process it somehow? Give it an URI? Cast it to some particular type?
I am aware, the svgjs library has a attachTo() method on their object. As this happens outside of angular and does not let me do everything I want to down the road, I would like to take things into my own hands.
I can also describe a little more what is not working. Using src={{svg}} or [src]="svg"
almost works as far as I can tell. But src is "unsafe".
<img _ngcontent-dgo-c96="" id="other" src="unsafe:<svg xmlns="http://www.w3.org/2000/svg"(...shortended...) </svg>">
Using the [style.background] approach creates an empty svg element and at the wrong position.
Upvotes: 1
Views: 377
Reputation: 402
in order to do that you need to
#svgContainer
)ViewChild
backgroundImage
I have provided a working solution here (see app.component.ts
and app.component.html
:
https://codesandbox.io/s/sleepy-buck-r13ck?file=/src/app/app.component.ts
Upvotes: 1