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

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>

Comments

-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

4 Comments

He asked how to change the class, not the style
What the heck, now it's not even valid syntax
That is for angularJS, not angular 2+. Maybe this still compiles in angular2+ but it is not standard syntax. I would not pass it in a code review. ngStyle is for modifying properties directly. ngClass is for modifying classes. Don't cross the streams.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.