Tutorial

The Many Ways To Use NgClass

Draft updated on Invalid Date
author

Chris on Code

The Many Ways To Use NgClass

This tutorial is out of date and no longer maintained.

Introduction

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 lets 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.

http://codepen.io/sevilayha/pen/qlLED/

In the past, we’ve looked at how we can use the ngShow and ngHide directives to adjust our DOM. Let’s go ahead and dive right into how we can use the ngClass directive.

Using ngClass

For our examples and tutorials here, we’ll be using input boxes (text and checkbox) to dynamically/conditionally add classes to our HTML elements.

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!

Here’s an example of binding a variable to the class using the string syntax:

http://codepen.io/sevilayha/pen/onfrd/

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!

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 }">

When evaluating an expression, you must use the

{} curly brackets so that Angular knows to evaluate that expression. To the left of the colon is the class that will be applied and to the right is the expression or variable that you want to be evaluated. The example at the very beginning of this article is using evaluated expressions. Here it is again. Take a look at the HTML for this demo to see how it’s done:

http://codepen.io/sevilayha/pen/qlLED/

Classes with Hyphens: When using classes with hyphens (like text-success or btn-lg) make sure you put single quotes around the class. Angular requires that the key must be a valid identifier like object literals in JavaScript. text-success is not valid which is why Angular requires the class.

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'">

The ternary operator is a great way to quickly define true and false conditions.

Evaluating First, Last or Specific Number

If you are using the ngRepeat directive and you want to apply classes to the first, last, or a specific number in the list, you can use special properties of ngRepeat. These include $first, $last, $even, $odd, and a few others. Here’s an example of how to use these:

<!-- add a class to the first item -->
<ul>
  <li ng-class="{ 'text-success': $first }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

<!-- add a class to the last item -->
<ul>
  <li ng-class="{ 'text-danger': $last }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

<!-- add a class to the even items and a different class to the odd items -->
<ul>
  <li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

Note: From the Bootstrap docs, text-success adds a green color and text-danger adds a red color to text.

You can see how these special classes can be useful when using the ngRepeat directive along with the ngClass directive.

ngClass Usage Options

There are two different ways you can use the ngClass directive: as a class and as an attribute. I personally prefer the attribute way so that it’s always clear which classes are coming from Angular and which are just basic static classes. We can take the three styles we’ve showcased above (string, array, and evaluated expression) and use them in both the class and attribute ways.

ngClass as a Class

You can add ng-class right into your HTML’s class attribute. Here’s an example:

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

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

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

ngClass as an Attribute

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

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

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

Both ways work and it’s all preference to how you want to use them.

Conclusion

This was a look at how you can use the useful ngClass directive in many different ways. Hopefully, this provides you the flexibility needed when building out your own applications.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Chris on Code

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.