Change label color dynamically in Ionic2


#1

favorite
I have a string property with values like “primary”, “secondary” or “danger”. I am able to bind it to a badge in this way:

<ion-badge class="badge badge-{{product.colorStock}}">1</ion-badge>

But I am not able to do the same with a label (this does NOT work):

<ion-label class="label label-{{product.colorStock}}">Text</ion-label>

How could I bind my property to the label so it changes its color?

Thank you


#2

Try using ‘ng-class’ instead of writing properties for regular classes. Here’s the Angular documentation on ng-class.

Cheers!


#3

I have tested it, and it does not work with ng-class too. Any other suggestion?

By the way, with badges instead of labels, it works with simple class but not with ng-class.

Thank you


#4

A bit unwieldy, but should work:

<ion-label 
[attr.primary]="product.colorStock == 'primary' ? '' : null" 
[attr.secondary]="product.colorStock == 'secondary' ? '' : null" 
[attr.danger]="product.colorStock == 'danger' ? '' : null">
Text
</ion-label>

#5

I have tested it, but I am afraid it does not work too…

Thank you anyway


#6

Please double-check things, because I verified that the fundamental concept works on a scratch project.


#7

Your are right… SORRY. I have checked it again and it was my project fault!! SORRY.


#8

<ion-badge [ngClass]="'badge-' + product.colorStock">{{product.text}}</ion-badge> should work


#9

Yes, with badges it works, but with labels it does NOT work.

Thank you