【问题标题】:Angular4 to use SVG with *ngForAngular4 将 SVG 与 *ngFor 一起使用
【发布时间】:2018-05-12 19:31:10
【问题描述】:

我正在尝试将 SVG 用于完美工作的字体图标。但是,我在使用*ngFor 时遇到了一个主要问题。这是我的代码

<ion-col col-3 *ngFor="let land of landscape_amenities>
    <span class="icon-{{land.id}}"></span><br />
    <span>{{land.name}}</span>
</ion-col>

现在,我正在尝试使用 SVG,但我不知道如何调用与 id 匹配的 SVG。 .ts 文件中有什么可以做的吗? id 是唯一的,目前未使用。

文件的输出是这样的:

<ion-col col-3="">
    <span class="icon-beds"></span>
    <br>
    <span>Beds</span>
</ion-col>
<ion-col col-3="">
    <span class="icon-sofa"></span>
    <br>
    <span>Sofa</span>
</ion-col>
....

我有超过 20 个 SVG 可以放入这个 *ngFor。这是我的床 ID 的 SVG 代码:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
    <g>
        <path d="M490.667,261.334v-42.667c0-32.427-20.907-53.333-53.333-53.333H192c-32.427,0-53.333,20.907-53.333,53.333V261
            L34.88,261.227H21.333V80.32c0-5.333-3.84-10.133-9.067-10.88C5.653,68.48,0,73.6,0,80v351.68c0,5.333,3.84,10.133,9.067,10.88
            c6.613,0.96,12.267-4.16,12.267-10.56v-64h469.333v63.68c0,5.333,3.84,10.133,9.067,10.88C506.347,443.52,512,438.4,512,432
            V282.667C512,268.16,505.173,261.44,490.667,261.334z M160,218.667c0-27.84,20.053-32,32-32h245.333c11.947,0,32,4.16,32,32
            v42.667H160V218.667z M490.666,346.667H21.333v-64h469.333V346.667z"/>
    </g>
    <g>
        <path d="M80.5,142.5c-32.723,0-59.25,26.527-59.25,59.25c0,32.723,26.527,59.25,59.25,59.25s59.25-26.527,59.25-59.25
            C139.75,169.027,113.223,142.5,80.5,142.5z M80.5,242c-22.229,0-40.25-18.021-40.25-40.25S58.271,161.5,80.5,161.5
            s40.25,18.021,40.25,40.25S102.73,242,80.5,242z"/>
    </g>
</svg>

【问题讨论】:

  • 你想把你的 SVG 放在哪里?在离子上?
  • 理想情况下,它应该用相应的 SVG 替换 &lt;span class="icon-beds"&gt;&lt;/span&gt;
  • 我猜你应该使用 。在这种情况下,您将使用 id 作为其名称的后缀保存您的 svg。
  • 是的,但我不知道该怎么做。你能告诉我该怎么做吗?像我可以遵循的示例来创建其余部分吗?我觉得路径必须在.ts文件中设置,但不确定从哪里开始。

标签: angular svg ionic-framework ionic2 ionic3


【解决方案1】:

您可以按照给定的代码:

<ion-col col-3 *ngFor="let land of landscape_amenities>
    <icon src="./assets/{{land.id}}"/><br />
    <span>{{land.name}}</span>
</ion-col>

在这里,我假设您的图片(按 id 的名称,即床、沙发)存在于 assets 文件夹中。

根据您的评论,您还可以使用 typescript 方法设置路径:

<icon [src]="getImageSource(land.id)"/>

然后在你的 ts 文件中创建一个方法:

getImageSource(svgId:String):String {
  return `./assets/$svgId`;
}

但我不建议您这样做,因为我猜您一旦分配就不会更改 svg 数据。因此,由于角度变化检测,它将多次调用该方法。因此,只需在模板本身中分配图像源,而不是在 .ts 文件中创建函数。

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2013-04-25
    • 2013-02-19
    • 2018-01-16
    相关资源
    最近更新 更多