620

ALERT: This thread is for the old AngularJS!

Can we have multiple expression to add multiple ng-class ?

for eg.

<div ng-class="{class1: expressionData1, class2: expressionData2}"></div>

If yes can anyone put up the example to do so.

.

Shadoweb
  • 5,812
  • 1
  • 42
  • 55
Aditya Sethi
  • 10,486
  • 11
  • 26
  • 31

12 Answers12

1105

To apply different classes when different expressions evaluate to true:

<div ng-class="{class1 : expression1, class2 : expression2}">
    Hello World!
</div>

To apply multiple classes when an expression holds true:

<!-- notice expression1 used twice -->
<div ng-class="{class1 : expression1, class2 : expression1}">
    Hello World!
</div>

or quite simply:

<div ng-class="{'class1 class2' : expression1}">
    Hello World!
</div>

Notice the single quotes surrounding css classes.

Community
  • 1
  • 1
AlwaysALearner
  • 43,759
  • 9
  • 96
  • 78
  • 17
    you can not pass multiple class like ng-class="{'class1 class2' : expression1}" just test that and did not worked at all, solution as @CodeHater said "To apply multiple classes when an expression holds true:" that made the trick – d1jhoni1b Jul 14 '14 at 22:51
  • 9
    In 1.2.16 the multi-class option (`'class1 class2': expression`) seems to work fine, except that if you reuse a class it is dropped when the expression toggles between the options. E.g. with `'commonClass class1': expression == true, 'commonClass class2': expression == false` commonClass is lost as the expression toggles between true and false. – BrianS Aug 01 '14 at 18:03
  • 10
    @BrianS I would do something like this: `class="commonClass" ng-class={'class1' : expression, 'class2' : !expression}` – AlwaysALearner Aug 03 '14 at 09:15
  • @CodeHater thanks. That's pretty much what I'm planning now, just need to take a moment to fix up the CSS. – BrianS Aug 04 '14 at 01:15
  • Is `ng-class="{'class1' : expression1, 'class2':expression1 }"` possible? Would you mind looking at my Question: http://stackoverflow.com/questions/25391692/adding-multiple-expressions-using-ng-class-in-angularjs – Danger14 Aug 19 '14 at 19:44
  • ng-class="{class1 : expression1, class2 : expression2}" condition is not working in safari. – Hardik Panseriya May 10 '16 at 10:57
  • What version of angular is this for? It is not working for me. – Noobie3001 Oct 13 '19 at 11:49
  • if you have a class name with hyphen in it, you have to use apostrophes around it, otherwise it's not going to work. – adrian.krzysztofek Oct 03 '20 at 10:45
  • Use ternary operator if you want to apply multiple class for the same condition for eg. [ngClass]="expression1 ? 'class1' : 'class2' " – sda87 Feb 14 '22 at 13:02
61

For the ternary operator notation:

<div ng-class="expression1? 'class1 class2' : 'class3 class4'">
shA.t
  • 16,580
  • 5
  • 54
  • 111
Razan Paul
  • 13,618
  • 3
  • 69
  • 61
55

An incredibly powerful alternative to other answers here:

ng-class="[  { key: resulting-class-expression }[ key-matching-expression ], ..  ]"

Some examples:

1. Simply adds 'class1 class2 class3' to the div:

<div ng-class="[{true: 'class1'}[true], {true: 'class2 class3'}[true]]"></div>

2. Adds 'odd' or 'even' classes to div, depending on the $index:

<div ng-class="[{0:'even', 1:'odd'}[ $index % 2]]"></div>

3. Dynamically creates a class for each div based on $index

<div ng-class="[{true:'index'+$index}[true]]"></div>

If $index=5 this will result in:

<div class="index5"></div>

Here's a code sample you can run:

var app = angular.module('app', []); 
app.controller('MyCtrl', function($scope){
  $scope.items = 'abcdefg'.split('');
}); 
.odd  { background-color: #eee; }
.even { background-color: #fff; }
.index5 {background-color: #0095ff; color: white; font-weight: bold; }
* { font-family: "Courier New", Courier, monospace; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

<div ng-app="app" ng-controller="MyCtrl">
  <div ng-repeat="item in items"
    ng-class="[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]">
    index {{$index}} = "{{item}}" ng-class="{{[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]].join(' ')}}"
  </div>
</div>
Kit
  • 3,388
  • 1
  • 27
  • 24
  • 2
    Brilliant answer! I've always used functions for more complex `ng-class` directives, such as when I needed to apply a ternary and a standard expression on the same element. I've submitted an edit to the accepted answer to include the use of arrays of expressions. – Daniel Bonnell Aug 19 '16 at 19:05
  • I'm not an Angular expert, but in seems that this construct: `[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]` can simplified like this `['index'+$index, {0:'even', 1:'odd'}[ $index % 2 ]]`. I've just tried it in Angular 1.5.9 and it works :) Thanks for a great answer! – vadipp Mar 12 '19 at 10:59
  • @kit can you pls help me here [Similar SO](https://stackoverflow.com/questions/65253111/fa-fa-icons-in-ng-class-with-ternary-operator-angular-js-1-x/65253772#65253772) – Mr. Learner Dec 15 '20 at 04:36
48

Yes you can have multiple expression to add multiple class in ng-class.

For example:

<div ng-class="{class1:Result.length==2,class2:Result.length==3}"> Dummy Data </div>
Sumit Gupta
  • 775
  • 7
  • 9
30

Using a $scope method on the controller, you can calculate what classes to output in the view. This is especially handy if you have a complex logic for calculating class names and it will reduce the amount of logic in your view by moving it to the controller:

app.controller('myController', function($scope) {

    $scope.className = function() {

        var className = 'initClass';

        if (condition1())
            className += ' class1';

        if (condition2())
            className += ' class2';

        return className;
    };
});

and in the view, simply:

<div ng-class="className()"></div>
Ahmad M
  • 1,061
  • 1
  • 11
  • 5
  • 1
    If the class changes after render, is ng-class still listening for changes in `className`? – remarsh Sep 30 '15 at 17:56
  • 3
    IMHO, the scope should only expose the _condition_. It should be up to the HTML `ng-` bindings to determine what _class_ to use when that condition is met. – Alnitak Feb 18 '16 at 11:46
  • 1
    This overwrites the class attribute in dom elements. If one uses this, they have to include the classes that don't need conditions in the returned `className`. – phuwin Jan 18 '17 at 09:20
23

Your example works for conditioned classes (the class name will show if the expressionDataX is true):

<div ng-class="{class1: expressionData1, class2: expressionData2}"></div>

You can also add multiple classes, supplied by the user of the element:

<div ng-class="[class1, class2]"></div>

Usage:

<div class="foo bar" class1="foo" class2="bar"></div>

seldary
  • 6,186
  • 4
  • 40
  • 55
  • 3
    Do you know if it is possible to combine the two types of template, ie have a conditional class using `{}` and a data-bound class using `[]`? – jwg Oct 27 '14 at 09:55
  • 4
    As far as I know it is not possible. Also, it is not possible to put two `ngClass` directives on an element. – seldary Oct 27 '14 at 10:01
  • Thanks! This seems to be confirmed elsewhere. – jwg Oct 27 '14 at 10:09
  • 2
    you'll be surprised: `` and more: http://scotch.io/tutorials/javascript/the-many-ways-to-use-ngclass – mayankcpdixit Dec 06 '14 at 19:29
  • 1
    @jwg : you can combine two types of templates ans is here : http://stackoverflow.com/questions/29230732/how-to-combine-conditional-class-and-data-bound-class-in-angularjs/29231252#29231252 – satish kumar V Mar 24 '15 at 11:36
12

Here is an example comparing multiple angular-ui-router states using the OR || operator:

<li ng-class="
    {
        warning:
            $state.includes('out.pay.code.wrong')
            || $state.includes('out.pay.failed')
        ,
        active:
            $state.includes('out.pay')
    }
">

It will give the li the classes warning and/or active, depening on whether the conditions are met.

nitech
  • 1,822
  • 3
  • 21
  • 35
6

Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.

ng-class="{'active' : itemCount, 'activemenu' : showCart}"
Vivek Panday
  • 1,426
  • 2
  • 16
  • 34
6

With multiple conditions

<div ng-class="{'class1' : con1 || can2, 'class2' : con3 && con4}">
Hello World!
</div>
Hemakumar
  • 639
  • 9
  • 24
5

Found another way thanks to Scotch.io

<div ng-repeat="step in steps" class="step-container step" ng-class="[step.status, step.type]" ng-click="onClick(step.type)">

This was my reference.PATH

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Emiliano Barboza
  • 475
  • 4
  • 11
3

Other way we can create a function to control "using multiple class"

CSS

 <style>
    .Red {
        color: Red;
    }
    .Yellow {
        color: Yellow;
    }
      .Blue {
        color: Blue;
    }
      .Green {
        color: Green;
    }
    .Gray {
        color: Gray;
    }
    .b {
         font-weight: bold;
    }
</style>

Script

<script>
    angular.module('myapp', [])
            .controller('ExampleController', ['$scope', function ($scope) {
                $scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
                $scope.getClass = function (strValue) {
                    if (strValue == ("It is Red"))
                        return "Red";
                    else if (strValue == ("It is Yellow"))
                        return "Yellow";
                    else if (strValue == ("It is Blue"))
                        return "Blue";
                    else if (strValue == ("It is Green"))
                        return "Green";
                    else if (strValue == ("It is Gray"))
                        return "Gray";
                }
        }]);
</script>

Using it

<body ng-app="myapp" ng-controller="ExampleController">

<h2>AngularJS ng-class if example</h2>
<ul >
    <li ng-repeat="icolor in MyColors" >
        <p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
    </li>
</ul>

You can refer to full code page at ng-class if example

Lewis Hai
  • 1,114
  • 10
  • 22
1

I use this:

[ngClass]="[{
    'basic':'mat-basic-button', 
    'raised':'mat-raised-button', 
    'stroked':'mat-stroked-button'
}[ 
    button.style ?? 'raised'
]]"