问题
I'm looping through list of employee objects in which each object has imageUrl and I need to use that image url in the svg - Image
<div *ngFor ="emp of employees">
<defs>
<pattern id = "attachedImage" height = "100%" width = "100%" patternContentUnits = "objectBoundingBox">
<image href="{{emp.ImageUrl}}" preserveAspectRatio = "none" width = "1" height = "1"/>
</pattern>
</defs>
<circle cx = "50%" cy = "50%" r = "35%" fill = "url(#attachedImage)"/>
</div>
I don't want to loop through all the html elements in JS. Even if I do, I want to map the appropriate image
Is there any way I can dynamically append that Url in this image I tried using {{emp.ImageUrl}} which didn't work.
This is the URL of working example where I've hardcoded the URL https://stackblitz.com/edit/angular-pq6r2w
I want to add the URL dynamically
Any suggestion would be appreciated!
回答1:
The problem in your markup is that you reuse the same id
for all pattern images. As a result, the first image is shown in all the shapes. You can use the ngFor
loop index to make each id
distinct:
<div *ngFor="let emp of employees; let i = index">
...
<svg class="circle-chart" ...>
...
<g class="circle-chart__info">
<defs>
<pattern [id]="'attachedImage_' + i" ... >
<image [attr.xlink:href]="emp.ImageUrl" ... />
</pattern>
</defs>
<circle [attr.fill]="'url(#attachedImage_' + i + ')'" ... />
</g>
</svg>
</div>
You can see the result in this stackblitz. Please note that I also set the https
protocol on the second image to make it visible in the view.
回答2:
I'm not quite sure if this is the right solution but it works for me.
You can try it like this:
[src]=emp.ImageUrl
来源:https://stackoverflow.com/questions/58733093/how-to-update-svg-image-href-dynamically-in-angular-html