Aw3same
Aw3same

Reputation: 1030

Angular 2 - Set bootstrap class depend of string value

I have a doubt and I don't know how to solve.I bring some data from server and show it on a table. One of these fields it's a string with values like 'OK', 'ERROR' or 'CANCEL'. It possible to assign some bootstrap classes depending of value? For example bg-succes if it 'OK' or bg-danger if 'CANCEL'.

Example:

<table class="table table-hover">
    <thead class="thead-inverse">
        <tr>
            <th class="text-center"><strong>Date 1/ Date 2</strong></th>
            <th class="text-center"><strong>Status</strong></th>
            <th class="text-center"><strong>Date 3</strong></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of items">
            <td class="text-center">  
              <tr class="text-center"> {{item.Date1}} </tr>
              <tr class="text-center"> {{item.Date2}} </tr>
            </td>
             <td class="text-center">
                <tr>Status</tr>
                <tr class="bg-success"> {{item.Status}}</tr>//Want to assign here the class                  
            </td>
            <td class="text-center"> {{item.Date3}} </td>            
        </tr>
    </tbody>
</table>

Thanks by the way!

Upvotes: 1

Views: 300

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You could achieve the same using ngClass directive.

<tr [ngClass]="getStatusClass(item.Status)"> {{item.Status}}</tr>

Code

getStatusClass(status: string){
   let statuses = {"OK": "bg-success", "ERROR": "bg-danger", "CANCEL": "bg-warning"}
   return statuses[status] || 'bg-default';
}

Upvotes: 2

Related Questions