1
votes

In my angular code, I am trying to assign a css color to my button and need to call a ts function to return the css class name.

I tried the following code

<button style="height: 10%" class="getColor(days.date)">{{days.date}}</button>

In my ts code,

I have something like this

getColor(item: any) {


    return 'bg-green'; // define in my style.css
  }

I quickly noticed that class="getColor()" does not even call the function.

I thought about ngIf and ngTemplate but not sure if that will work. I using setting to 4 different colors as indicators like default gray, blue, red, and yellow.

Any help is appreciated. Thanks.

3

3 Answers

2
votes

You should use ngClass

<button style="height: 10%" [ngClass]="getColor(days.date)">{{days.date}}</button>

Repro

0
votes

In order to call the function you need to use property binding like this

<button style="height: 10%" [class]="getColor(days.date)">{{days.date}}</button>
0
votes

If you want to toogle classes based on a condition you can use ngClass, like in the following example:

<div [ngClass]="{
   'example-class': condition;
   'another-class': getColor(days.date)
  }">
</div>

Or:

<div [example-class]="condition ? 'example-class' : 'other-class'"></div>