In Ionic (3), how can I programmatically set the text color of an item?
For example, clicking on a list item will change (toggle) the color of the list item.
<ion-content>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let element of elements" #listitem (click)="changeTextColor(listitem)">
Click to change text color of {{element}}
</ion-item>
</ion-list>
</ion-content>
With the code of the changeTextColor:
changeTextColor( listitem) {
console.log( 'changing text color');
listitem._color="danger";
}
So this seems to be a "Restyle X when Y happens"-question, I'll try to explain the steps to resolve a task like this in general. I've answered a simpler question like this here, which might also help to get started.
Solving theese kind of problems normally includes following steps:
Define CSS classes
So first of all we'll have to find the states we want to display. These often reflects states in our business logic. For the sake of demonstration I'll take your example of only two state danger and normal. This could also be pending, complete and overdue (see my other answer above) or anything else.
Now we're going to define CSS classes for every state. I your case this could look something like this:
Of course we could also style the
background-color
or anything else here.If you want to reuse colors defined in
variables.scss
, you can use themap-get
function like so:Assign one of the defined CSS classes
Now we can assign our initial CSS class to the elements we want to style. This is pretty straight forward using the
class
operator:Store the current state/CSS class
Next we need to store our current state/CSS class, so we can handle changes to it. In your case we'll have to turn the elements we're iterating over with
*ngFor
into objects with a property to store our current CSS class (we'll call this propertystate
):If you're already using objects just add a property storing your state.
We'll have to update our HTML to reflect our changes in the code:
Handle changes
We're already setting our state/CSS class dynamically, but how to handle changes? Therefore we'll create a method with our logic:
And use it in our HTML:
Also see this Stackblitz for a runnable version of above code.