Change color of badge programmatically


#1

I’m trying to change the color of a badge programmatically like I changed colors of other components before.

I used in html the following code:

<ion-badge item-end [color]="getColor(value)">{{ value }}</ion-badge>

In typescript there is the following code:

getColor(value) {
  switch (true) {
    case (value < 20):
      return '#4CB172';
    case (value < 33.33):
      return '#ff8800';
    default:
      return '#ff0000';
  }
}

But the color will never changes. It is always the primary color of my app. What can I do? Thank you for your help!


#2

I would try [attr.color] instead of [color]. If it works, I would also recommend updating an object property when the value changes instead of doing this in a function called from the template. If you really don’t want to do that, then I would suggest considering using the OnPush change detection strategy.


#3

Thank you for your fast reply! But this doesn’t work, too.


#4

Can you change the colour of the badge using Chome’s Dev Tools?

And, try:

<ion-badge [class]="..."

#5

But what is the needed property to set the wanted color in css?


#6

Hello,

one question: If you put a console.log(value) into your code, what will it log?.

getColor(value) {
console.log(value);
  switch (true) {
    case (value < 20):
      return '#4CB172';
    case (value < 33.33):
      return '#ff8800';
    default:
      return '#ff0000';
  }

Best regards, anna-liebt


#7

I tried yesterday before opening this topic. It was okay and I added an extra ion-item to get the returned value of getColor() and it was as wanted, too.


#8

The name of a class.

.scss:


...

$blue:       #488aff;
$green:      #4DB6AC;

.ios, .md, .wp {

  ...

  .green-badge {
    color: $green;
  }

  .blue-badge {
    color: $blue;
  }

  ...

}

For example, .ts:

public badgeColour: string = 'blue-badge';

.html:

<ion-badge item-end [class]="badgeColour">{{ value }}</ion-badge>

See: https://robferguson.org/blog/2018/04/09/theming-your-ionic-3-app-bespoke-svg-icons/


#9

Hello,
okay you have tried it yesterday.
And what is console.log(value) now?

Best regards, anna-liebt