Search code examples
cssangularng-class

dynamic css class on a span element - angular 4


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


Solution

  • <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