RRB
RRB

Reputation: 2116

Change class dynamically in Angular

I have a list which renders dynamically using a ngFor directive. The data comes from an SQL Lite DB. I am trying to append a class to each list item based on the data present. i.e if the list item is an "Expense" then append a red class, if the list item is an "Income" then append a green class. I have found a similar question here but it only checks for true/false and not exact text.

My code is as follows

<ion-item-sliding *ngFor="let expense of expenses; let i=index">
  <ion-item nopadding [ngStyle]="{greenClass: expense.type==='Income', redClass: expense.type==='Expense'}">
    <p>
      <span>Day of month: {{expense.day}}</span><br>
      Type: {{expense.type}}<br>
      Description: {{expense.description}}
    </p>
    <h3 item-end>
      Amount: R{{expense.amount}}
    </h3>
  </ion-item>
</ion-item-sliding>

Upvotes: 0

Views: 223

Answers (1)

Yashwardhan Pauranik
Yashwardhan Pauranik

Reputation: 5556

You are using ngStyle instead of ngClass.

<ion-item-sliding *ngFor="let expense of expenses; let i=index">
  <ion-item nopadding [ngClass]="{greenClass: expense.type==='Income', redClass: expense.type==='Expense'}">
    ...
  </ion-item>
</ion-item-sliding>

Upvotes: 3

Related Questions