Changing color of item depending on its category


First of all I’m new to Ionic, please be kind :slight_smile:

I would like to set the color of the ion-badge depending on its category.

I’ve tried this

<ion-badge [color]="setColor()">{{ api.getCatName(item.categories[0]) }}</ion-badge>

and in home.ts

  setColor() {
    if (this.category_id == 93) {
      return 'secondary';
    } else {
      return 'primary';

But it doesn’t work.

Could someone help me figure what I’m doing wrong ?

Thank you :slight_smile:

Please refactor your code so that there are no function calls in the template.

Thank uou for the answer @rapropos I wish I could but what if I want to change the color of the navbar of example, depending on the content ?

I think what he means is change the function “setColor()” to a variable, and then use “setColor()” in your home.ts file to set that variable.

1 Like

Try this:

<ion-badge [color]="item.category_id == 93? 'secondary' : 'primary' ">{{ api.getCatName(item.categories[0]) }}</ion-badge>

Also indeed try not to use functions inside bindings and interpolations (like api.getCatName(item…) }} - is a bad practice.