Dynamically change color in <ion-icon>

I’m using the ionic-conference-app to test how to dynamically change the color on the menu icons but I don’t seem to get it to work. Here’s what I did:

I modified the app.ts to include a color element

interface PageObj {
  title: string;
  component: any;
  icon: string;
  color: string;
  index?: number;
}

// create an list of pages that can be navigated to from the left menu
// the left menu only works after login
// the login page disables the left menu
this.appPages = [
  { title: 'Schedule', component: TabsPage, icon: 'calendar', color: 'danger', },
  { title: 'Speakers', component: TabsPage, index: 1, icon: 'contacts', color: 'primary', },
  { title: 'Map', component: TabsPage, index: 2, icon: 'map', color: 'secondary', },
  { title: 'About', component: TabsPage, index: 3, icon: 'information-circle', color: 'dark', },
];

And I tried different things on the markup app.html but nothing worked. Here are a few things I tried

<ion-icon item-left [name]="p.icon" [attr.p.color]="loggedIn ? '' : null"></ion-icon> (didn’t work)

<ion-icon item-left [name]="p.icon" [ngClass]="p.color"></ion-icon> (didn’t work)

<ion-icon item-left [name]="p.icon" p.color></ion-icon> (didn’t work)

Any ideas?

1 Like

The icons are rendered as a font. So i suppose doing something like <ion-icon name="home" [ngStyle]="{'color':p.color}"></ion-icon> this would do the trick.

4 Likes

@luukschoen thanks for the reply, but it didn’t work. Here’s the markup

<ion-icon item-left [name]="p.icon" [ngStyle]="{'color':p.color}"></ion-icon>

1 Like

Sorry, you had me a little confused. If you want a different color, I’m pretty sure my answer is the way to go. But you are referencing color with a class based name, that won’t work. Replace it with the hexadecimal value of the color you want to use, or just use green or something.

If you replace p.color with ‘green’ in the snippet I gave you, it should definitely work.

2 Likes

You’re absolutely right. It works! Thank you very much for your help :+1:

1 Like