Search code examples
cssangularjsng-classng-style

AngularJS dynamic styling with extended class


I am trying to display a status label that will contain different background colors and text depending on the status in AngularJs (e.g. 'New' = green, 'Active' = yellow). I currently have a css file with

.status {
    padding: 4px 8px;
    font-size: 12px;
    line-height: 12px;
    color: white;
    border-radius: 16px;
}

.status.new {
    background-color: #673AB7;
    border: 1pt solid #673AB7;
}

.status.active {
    background-color: #4CAF50;
    border: 1pt solid #4CAF50;
}

In my html I am referencing multiple classes like below

<span class="status pull-right">{{statusProperty}}</span>

Is it possible to combine class with ng-class to use extended classes or can this be accomplished through ng-style?


Solution

  • Yes, you can use ng-class along with class

    In your case it would go like this:

    <span class="status pull-right" ng-class="{'new': <condition_for_being_green>, 'active': <condition_for_being_yelow>}">{{statusProperty}}</span>
    

    This will make your element to have the classes status and pull-right through the class attribute and to have the new | active classes when the conditions for being green and yellow are met respectively.

    It means the element will have the classes

    • status pull-right new if the <condition_for_being_green> is true
    • status pull-right active if the <condition_for_being_yellow> is true
    • status pull-right new active if the <condition_for_being_green> and <condition_for_being_yellow> are true
    • status pull-right if the <condition_for_being_green> and <condition_for_being_yellow> are false