3

I'm trying to dynamically add icon names to my Ionic 2 app, the reason for this is that I have a list of attributes on my model, which are dynamic, the model returns the icon name to the ionic 2 application.

This is the response I'm getting from my API.

{
  "type": "searchresult",
  "count": 1,
  "results": [
    {
      "type": "room",
      "url": "/api/room/1",
      "id": 1,
      "name": "name1",
      "attributes": [
        {
          "type": "attribute",
          "url": "/api/room/1/attribute/1",
          "name": "attribute1",
          "icon": "people",
          "valueType": "bool",
          "value": "true"
        },
        {
          "type": "attribute",
          "url": "/api/room/1/attribute/3",
          "name": "attribute2",
          "icon": "desktop",
          "valueType": "bool",
          "value": "true"
        },
        {
          "type": "attribute",
          "url": "/api/room/1/attribute/4",
          "name": "attribute3",
          "icon": "md-videocam",
          "valueType": "bool",
          "value": "true"
        },
        {
          "type": "attribute",
          "url": "/api/room/1/attribute/5",
          "name": "attribute4",
          "icon": "icon-chair",
          "valueType": "int",
          "value": "200"
        }
      ]
    }
  }

This is what I have in the Ionic2 app at the moment.

<ion-row no-padding *ngFor="let att of room.attributes">
    <ion-col width-20 no-padding text-center>
        <ion-icon name="att.icon"</ion-icon>
    </ion-col>
</ion-row>

Thank you in advance.

Wesley Coetzee
  • 4,768
  • 3
  • 27
  • 45

4 Answers4

13

What happens here is that when you use name="att.icon" you're just passing the plain word att.icon to your name attribute, but in this case att is an object and icon is a key of this object.

That said, you want to use property binding like [name] instead of name:

<ion-icon [name]="att.icon"></ion-icon>

Compiler now will evaluate the value of the expression and assigns the value to the name.

Check the demo:

PLUNKER


Other questions:

developer033
  • 24,267
  • 8
  • 82
  • 108
3

Another way which I use is :

<ion-icon name={{att.icon}}></ion-icon>

Same thing works for src of img tag also

<img src={{att.image}}/>
Sagar Kulkarni
  • 2,072
  • 2
  • 16
  • 25
0

You can use it like <ion-icon name="{{att.icon}}"></ion-icon>.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
usman
  • 3
  • 2
0

When data has come from ngFor I've had to use this before :

[attr.name]="ngForItem.name"

(using your code) :

<ion-row no-padding *ngFor="let att of room.attributes">
    <ion-col width-20 no-padding text-center>
        <ion-icon [attr.name]="att.icon"</ion-icon>
    </ion-col>
</ion-row>
HazeyAce
  • 361
  • 3
  • 12