The Many Ways To Use ngClass

AngularJS provides some great features to help us create interactive applications. They provide things called directives in order to change the DOM and attach specific Angular behaviors to an element we specify.

Today we’ll be looking at the ngClass directive. This directive let’s us do awesome things like:

  • Add/Remove classes based on Angular variables
  • Add/Remove classes based on evaluated expressions
  • Bind single or multiple classes based on dynamic data

Here’s a quick example of some fun stuff you can do by dynamically adding classes.

ngClass Using String Syntax

This is the simplest way to use ngClass. You can just add an Angular variable to ng-class and that is the class that will be used for that element.

<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">

<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!</div>

ngClass Using Evaluated Expression

A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true, you can apply a certain class. If not, then the class won’t be applied.

<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?

<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">


ngClass Using Array Syntax

This is similar to the string syntax method except you are able to apply multiple classes.

<!-- both input boxes below will be classes for the div --> <input type="text" ng-model="styleOne"> <input type="text" ng-model="styleTwo"> <!-- this div will take on both classes from above --> <div ng-class="[styleOne, styleTwo]">Look! I'm Words!</div>


ngClass Using the Ternary Operator

The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:

ng-class="$even ? 'even-row' : 'odd-row'">

And an explanation example:

ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
ngClass as an Attribute

<!-- example with string syntax -->
<!-- use the type variable as a class -->
<div class="item" ng-class="type">Stuff Goes Here</div>

<!-- example with string syntax -->
<!-- use the styleOne and styleTwo variables as classes -->
<div class="item" ng-class="[styleOne, styleTwo]">Stuff Goes Here</div>

<!-- example with evaluated data -->
<!-- add the text-error class if wrong is true -->
<div class="item" ng-class="{ 'text-error': wrong }">Stuff Goes Here</div>

Happy Coding Smile