How to get ons-icon to load the icon dynamically?

2019-07-25 11:14发布

问题:

I've been having an issue with using the ons-icon and angular2 for a while.

<span *ngFor="let theIcon of item.getItem().style.get('icon')">
   <ons-icon [icon]="theIcon"></ons-icon> {{theIcon}}
</span>

While {{theIcon}} does display the proper icon text (md-cutlery), ons-icon never shows the icon. If I copy the text into the control and change it to icon="md-cutlery", it displays fine.

What am I missing?

回答1:

In Angular2 you have different directives to create bindings, you have directives for Attribute, Class, and Style Bindings. Since you want to create an attribute binding you need to do:[attr.icon]="myIconVar"

So your code should be:

<span *ngFor="let theIcon of item.getItem().style.get('icon')">
   <ons-icon [attr.icon]="theIcon"></ons-icon> {{theIcon}}
</span>