1

I have a span element in table. I want to change the css class dynamically based on the value.

Here's my html code:

    <table>
          <thead>
               <tr>
                  <th>Fruits</th>
                  <th>Colors</th>
               </tr>
          </thead>
          <tbody>
          <tr *ngFor="let data of fruits>
             <td>{{data.fruits}}</td>
             <td>
             <span class="badge badge-default badge-success">{{data.color}}</span>
             </td>
           </tr>
          </tbody>
</table>

I want to show the badge color based on data I get. For example if I get red, I want to change the badge class to badge-danger. If I get green, I want to change the class to badge-success and so on.

How do I achieve that in angular 4?

Thanks

Mustkeem K
  • 8,158
  • 2
  • 32
  • 43
yer
  • 1,454
  • 2
  • 16
  • 33

4 Answers4

4
<span class="badge badge-default" [ngClass]="{'badge-danger': data.color === 'red', 'badge-success': data.color === 'green' }></span>

You can use the ngClass directive in angular. The arguments are 'class-name':condition , if condition is true, then class-name is added to the element.

read more about ngClass here: https://angular.io/api/common/NgClass

Our_Benefactors
  • 3,220
  • 3
  • 21
  • 27
1

Try this way

<span class="badge badge-default" [ngClass]="{
    'badge-success':data.color === 'green',
    'badge-warning':data.color === 'yellow',
    'badge-success-danger':data.color === 'red'
  }">
  </span>
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
1

1) what if the value comes from an enum value in the object 2) is there a way to put all the ngClass logic in a component method and do soemthing like:

<tbody>
    <tr *ngFor="let task of tasks">
        <td>{{ task.title }}</td>
        <td>{{ task.description }}</td>
        <td>
            <span class="label" [ngClass]="{ getTaskLabel(task) }" >task.taskstate</span>
        </td>
        <td>
    </tr>
</tbody>
Alex Mtz
  • 11
  • 1
-1
<span class="badge badge-default badge-success" [ngStyle]="data.color =='red' ? {'class': 'badge badge-danger'} : {'class': 'badge badge-success'}"></span>

You can use ngStyle property and ternary operator with the same something like what i have provided

Vaibhav
  • 1,481
  • 13
  • 17