Adding multiple class using ng-class

AngularjsNg Class

Angularjs Problem Overview


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.

.

Angularjs Solutions


Solution 1 - Angularjs

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.

Solution 2 - Angularjs

For the ternary operator notation:

<div ng-class="expression1? 'class1 class2' : 'class3 class4'">

Solution 3 - Angularjs

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>

Solution 4 - Angularjs

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>

Solution 5 - Angularjs

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>

Solution 6 - Angularjs

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>

Solution 7 - Angularjs

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.

Solution 8 - Angularjs

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

ng-class="{'active' : itemCount, 'activemenu' : showCart}"

Solution 9 - Angularjs

With multiple conditions

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

Solution 10 - Angularjs

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

Solution 11 - Angularjs

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

Solution 12 - Angularjs

I use this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAditya SethiView Question on Stackoverflow
Solution 1 - AngularjsAlwaysALearnerView Answer on Stackoverflow
Solution 2 - AngularjsRazan PaulView Answer on Stackoverflow
Solution 3 - AngularjsKitView Answer on Stackoverflow
Solution 4 - AngularjsSumit GuptaView Answer on Stackoverflow
Solution 5 - AngularjsAhmad MView Answer on Stackoverflow
Solution 6 - AngularjsseldaryView Answer on Stackoverflow
Solution 7 - AngularjsnitechView Answer on Stackoverflow
Solution 8 - AngularjsVivek PandayView Answer on Stackoverflow
Solution 9 - AngularjsHemakumarView Answer on Stackoverflow
Solution 10 - AngularjsEmiliano BarbozaView Answer on Stackoverflow
Solution 11 - AngularjsLewis HaiView Answer on Stackoverflow
Solution 12 - AngularjsManuel VillarroelView Answer on Stackoverflow