Angular4使用带有* ngFor的SVG

时间:2017-11-29 07:02:48

标签: angular svg ionic-framework ionic2 ionic3

我正在尝试将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>

1 个答案:

答案 0 :(得分:0)

您可以按照给定的代码:

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

我假设您的图片(按ID名称,床位,沙发)出现在资产文件夹中。

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

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

在ts文件中,您将创建一个方法:

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

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