DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Beyond the Chatbot: Engineering a Real-World GitHub Auditor in TypeScript
  • A Guide to Parallax and Scroll-Based Animations
  • Subtitles: The Good, the Bad, and the Resource-Heavy

Trending

  • Evolving Spring Boot APIs to an Event-Driven Mesh
  • Manual Investigation: The Hidden Bottleneck in Incident Response
  • Java in a Container: Efficient Development and Deployment With Docker
  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  1. DZone
  2. Coding
  3. JavaScript
  4. JavaScript for Beginners: Assigning Dynamic Classes With ngClass

JavaScript for Beginners: Assigning Dynamic Classes With ngClass

In this tutorial, we'll go over some of the most common ways to dynamically assign a CSS class to an element using the ngClass directive.

By 
DZone Editorial user avatar
DZone Editorial
·
Nov. 20, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.8K Views

Join the DZone community and get the full member experience.

Join For Free

In web apps it's a common requirement to tailor an element's appearance based on a condition. There are a few ways of accomplishing this, but if you're working with Angular, your choice is clear. The ngClass directive provides a myriad of ways to dynamically assign class names to elements or components. Its syntax is both concise and yet supports fairly complex logic to provide us with fine-grained control over both our class names as well as the criteria for setting them. 


Programming With JavaScript | Enroll in Free Online Course Today*

*Affiliate link. See Terms of Use.


In this tutorial, we'll go over some of the most common ways to dynamically assign a CSS class to an element using the ngClass directive.

Assigning a CSS Class Using [className] Property Binding

Although this article is about the ngClass directive, it is worth noting that, in many cases, you won't even need it! Thanks to [className] property binding, we can set a class via the native JavaScript className property, using the [] binding syntax. We can execute any statement inside of that binding that results in a string. This allows us to set one or more classes based on a condition:

JavaScript
 
<div [className]="isActive ? 'active-class' : 'inactive-class'"></div>


We could also build the class name at runtime:

JavaScript
 
<div [className]="'class' + someValue"></div>


Read: 5 JavaScript Concepts Every Web Developer Should Learn

Class Toggling via [className] Property Binding

Some consider the above class toggling technique to be a little more complicated than it needs to be as the inactive-class would probably be the default. If you fall into that camp, you can employ the [class.class-name] syntax to supply a condition to be evaluated:

JavaScript
 
<div 
  class="inactive" 
  [class.active]="isActive">
</div>


So, if we can conditionally set a class using [className] Property Binding, why do we even need the ngClass directive? As we'll see, the real reason to use the ngClass directive is that it can help us choose between multiple classes.

A Deep Dive into the ngClass Directive

Before we get into how to use the ngClass directive, it would be instructive to look at its definition:

JavaScript
 
@Input('class')
klass: string

@Input()
ngClass: string | string[] | Set<string> | { [klass: string]: any; }


Looking at the above code, we can now see that the [class] syntax that used earlier is actually part of the ngClass directive, via @Input('class'). Also notice that the ngClass directive gives us no less than four options for setting dynamic classes! 

Let's look at each of these in more detail.

Supplying a string or string[]

Assigning a string or string array to ngClass allows us to bind dynamic classes to Angular variables. Suppose that we had a variable called activeClass. Inside our .ts file, we can set to a known class name such as "text-success" or "text-failure" based on the result of some operation:

JavaScript
 
<div 
  [ngClass]="activeClass">
</div>


The array syntax is useful for applying multiple classes to the same element or component:

JavaScript
 
<div 
  [ngClass]="[activeClass, openClass]">
</div>


Using an Evaluated Expression

A slightly more advanced - yet highly useful - method of using ngClass is to provide an expression. The provided class is only applied if a variable or expression evaluates to true. To supply an expression, you must provide an object using curly brackets {}. To the left of each colon - the property name - is the class that will be applied; to the right - the property value - is the expression or variable that you want to be evaluated. Here's an example:

JavaScript
 
<!-- input box to toggle a variable to true or false -->
<input type="checkbox" [ngModel]="redText"> Toggle red text.
<input type="checkbox" [ngModel]="largeFont"> Toggle large text.

<div [ngClass]="{ 'text-red': redText, 'text-large': largeFont }">


Read: React, Angular, and Vue.js: What's the Technical Difference?

Using the Ternary Operator

The ternary operator lets you assign a value to a variable based on a boolean expression — either a boolean field, or a statement that evaluates to a boolean result. At its most basic, the ternary operator, also known as the conditional operator, can be used as an alternative to the if/then/else statement when setting a variable. 

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

JavaScript
 
[ngClass]="expression or variable ? true class : false class"


Here is some code that employs the ternary operator to set a DIV's class depending on whether or not two variables are equal:

JavaScript
 
<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">


The Set<string> ngClass Signature: Unwanted and Unloved

Set is a new data structure introduced in ES6, similar to Map. A typescript Set allows us to store distinct values into a List using methods such as add(), has(), and delete(). For whatever reason, the Set<string> ngClass signature never really caught on. I have never used it, nor do I know of anyone who has. 

Having said that, the Set should contain strings representing class names to apply to the element or component. Here's some typescript code that creates a Set named classes:

TypeScript
 
//Declare a Class member variable
public classes = new Set();
 
//Add class names
classes.add('active').add('text-large');


Conclusion

In this tutorial, we went over some of the most common ways to dynamically assign a CSS class to an element using the ngClass directive. As you can see, it's pretty powerful stuff. 

CSS JavaScript TypeScript

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Beyond the Chatbot: Engineering a Real-World GitHub Auditor in TypeScript
  • A Guide to Parallax and Scroll-Based Animations
  • Subtitles: The Good, the Bad, and the Resource-Heavy

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook