【问题标题】:Add dynamic value (from Angular) in an svg icon在 svg 图标中添加动态值(来自 Angular)
【发布时间】:2021-12-09 03:38:16
【问题描述】:

我有一个 svg 图标,我想在其中显示打字稿变量的值。该变量来自一个api。这可能吗??

svg:<svg id="Component_102_1" data-name="Component 102 – 1" xmlns="http://www.w3.org/2000/svg" width="32" height="20" viewBox="0 0 32 20"> <rect id="Rectangle_1674" data-name="Rectangle 1674" width="32" height="20" rx="10" fill="#0e70c7"/> </svg>

ts:this.countLife = this.filterLifePolicies.length;

html:<img class="ppp" id="what" src="../../assets/images/Component102_1.svg">

所以,我需要以某种方式将 countLife 的内容传递到该 svg 中。

【问题讨论】:

  • ...好吧,您是否尝试过为道具进行字符串插值,`
  • 是的..它没用
  • 好的,尝试属性绑定:<svg [attr.data-something]="countLife" .. >
  • 我在模板中做了以下操作:<img [innerHTML]="countlife" class="ppp" id="what" src="../../assets/images/Component102_1.svg"> 它没有出现但是当我检查时我看到了值
  • 可以使用 Angular 绑定修改 SVG。首先,如果通过img HTML 标记包含 SVG,则无法执行此操作。而是将 SVG 的 XML 粘贴到您的模板中,然后添加属性绑定。

标签: html angular web svg


【解决方案1】:

这是可能的。 只需将 SVG 的代码粘贴到模板中,然后将组件数据绑定到 SVG 元素即可。

例如如何修改 SVG 的高度(以像素为单位的速记设置):

<svg xmlns="http://www.w3.org/2000/svg" [attr.height.px]="heightInPixels"></svg>

请注意,heightInPixels 是在您的组件类中定义的变量。

编辑:

如果您想将某个变量值显示为文本,请尝试使用 Angular binginds 将 &lt;text&gt; node 添加到您的 SVG 中。

<text x="20" y="35" class="small">{{ myVariable}}</text>

请注意,xy(或任何其他属性)您可以按照前面[attr.x] 等所示的方式进行修改。

【讨论】:

  • 谢谢!但我不明白在我的情况下我必须绑定什么......所以它将是 [???] = "countLife" 我只想将 countLife 值显示到该 svg 中
  • 抱歉@AndreasV 迟到了评论。我不是修改或创建 SVG 的专家,但也许 &lt;text&gt; node 会帮助你实现你想要的?编辑了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2011-04-22
相关资源
最近更新 更多