【问题标题】:How to update SVG Image href dynamically in angular html?如何在 Angular html 中动态更新 SVG Image href?
【发布时间】:2020-03-03 02:39:42
【问题描述】:

我正在遍历员工对象列表,其中每个对象都有 imageUrl,我需要在 svg - Image 中使用该图像 url

<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>

我不想遍历 JS 中的所有 html 元素。即使我这样做,我也想映射适当的图像

有什么方法可以在这张图片中动态附加该网址 我尝试使用无效的 {{emp.ImageUrl}}。

这是我对 URL 进行硬编码的工作示例的 URL https://stackblitz.com/edit/angular-pq6r2w

我想动态添加网址

任何建议将不胜感激!

【问题讨论】:

  • 放入stackblitz
  • @dota2pro 我已经用 stackblitz 更新了

标签: javascript css angular svg css-animations


【解决方案1】:

您的标记中的问题是您对所有图案图像重复使用相同的id。结果,第一张图像以所有形状显示。您可以使用ngFor 循环索引使每个id 不同:

<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>

您可以在this stackblitz 中查看结果。请注意,我还在第二张图片上设置了https 协议,以使其在视图中可见。

【讨论】:

  • 非常感谢!
  • 您好,请检查一下! stackoverflow.com/questions/58742040/…
  • 我想补充一点,在图像上绑定 href 属性时,不要使用 XSS 转义 URL。它会告诉你使用属性绑定,而你不能。
【解决方案2】:

我不太确定这是否是正确的解决方案,但它对我有用。

你可以这样试试:

[src]=emp.ImageUrl

【讨论】:

    猜你喜欢
    • 2019-04-14
    • 2021-11-19
    • 1970-01-01
    • 2023-03-22
    • 2019-09-14
    • 2019-05-03
    • 2020-09-03
    • 2020-06-28
    • 2012-09-07
    相关资源
    最近更新 更多