NgClass in Angular with Examples

Learn via video courses
Topics Covered

Overview

NgClass is a pivotal directive in Angular, a widely-used Typescript framework. It empowers developers to dynamically apply CSS classes to HTML elements based on specific conditions or expressions. By binding to NgClass, you can seamlessly alter the styling of elements in response to changes in your component's data or user interactions. This directive simplifies class name management, enhancing the dynamism and responsiveness* of your Angular application. NgClass proves invaluable when handling conditional formatting, toggling styles, or managing user interactions such as button clicks**. Its concise syntax and flexibility contribute to the versatility and interactivity of your Angular web applications.

What is NgClass in Angular?

In Angular, NgClass is a fundamental and versatile directive designed to facilitate dynamic manipulation of CSS classes within HTML elements. It plays a crucial role in enhancing the interactivity and responsiveness of Angular applications. NgClass enables developers to apply CSS classes conditionally based on specific criteria, expressions, or user interactions, without the need for complex JavaScript code.

At its core, NgClass simplifies class management by allowing you to bind HTML elements to a set of class names. These class names can be determined dynamically, reacting to changes in the component's data or user actions. This dynamic class binding is exceptionally useful for various scenarios, such as changing styles in response to user input, highlighting active elements in a list, or toggling the appearance of components based on specific conditions.

The syntax for using NgClass is concise and easy to understand, making it accessible to developers at all skill levels. By leveraging this directive, Angular applications can adapt and transform their user interfaces in real-time, resulting in a more engaging and user-friendly experience.

What are Directives?

Directives in web development, particularly in frameworks like Angular, are special markers in the HTML code that instruct the framework to perform certain actions or apply specific behaviors to elements. They extend HTML's capabilities by introducing new syntax or functionalities.

There are three main types of directives:

  1. Component Directives: These create custom HTML elements with associated logic, encapsulating both the user interface and the behavior. Components are building blocks for web applications, allowing you to create reusable and modular pieces of your interface.
  2. Attribute Directives: These modify the appearance or behavior of existing HTML elements. Common use cases include dynamically updating element styles, adding or removing classes conditionally, or validating user input.
  3. Structural Directives: These change the structure of the HTML by adding or removing elements based on conditions. Examples include ngIf for conditional rendering and ngFor for iterating through lists and generating repeated content.

How to Use ngClass in Angular?

The ngClass directive in Angular is a powerful tool for dynamically binding one or more CSS classes to HTML elements. It allows you to apply styles conditionally based on specific criteria, such as user interactions or data-driven changes. This tutorial will guide you through the various ways to use ngClass in Angular.

1. Basic Usage of ngClass as a String

In its simplest form, you can use ngClass as a string to bind one or more CSS classes to an element. Here's a step-by-step guide:

Add a Title or Header

First, create an HTML header in your component's template file (e.g., app.component.html):

This example uses Angular Material's <mat-toolbar> for the header.

Define CSS Classes

In your component's CSS file (e.g., app.component.css), define the CSS classes you want to apply:

Apply CSS Classes Using ngClass

Now, bind the CSS classes to HTML elements using ngClass in your component's template:

The CSS class names are enclosed in single quotes within the ngClass directive.

Serve Your Project

Run the following command to serve your Angular project:

This command will open your project in the default web browser, and you'll see the applied styles based on the ngClass directive.

2. Using ngClass with Multiple CSS Classes

You can bind multiple CSS classes in a single ngClass directive, allowing you to combine styles. Update your component's HTML and CSS files as follows:

Define Additional CSS Classes

In your component's CSS file (app.component.css), add more CSS classes:

Apply Multiple CSS Classes

Now, bind multiple CSS classes using a space-separated string within the ngClass directive:

In this example, the first, second, and third classes are applied to the <div>, and the fourth class is applied to the <p>.

Serve Your Project

Serve your project again to see the updated output with multiple CSS classes applied.

3. Using ngClass with an Array

You can also use ngClass with an array to dynamically apply classes based on conditions. Here's how to do it:

Update Your Component's HTML

In your component's template file (app.component.html), use an array to define the CSS classes:

The CSS classes are enclosed in square brackets as an array.

Serve Your Project

Serve your project once more to see the output with classes applied from the array.

4. Using ngClass with an Object

The ngClass directive can also be used with an object to conditionally apply classes based on boolean values. Here's how:

Modify Your Component's HTML

In your component's template file (app.component.html), use an object where keys represent class names, and values determine whether the class should be applied:

In this example, the first class will be applied because its value is true, while the second class will not be applied because its value is false.

Serve Your Project

Serve your project to view the results. You can experiment with different combinations of boolean values to conditionally apply classes.

5. Conditional Classes with Ternary Operators and Objects

While you cannot use traditional if statements within ngClass, you can achieve conditional class application using ternary operators and objects. Here are some examples:

Conditional Class Based on a Value

You can use a ternary operator to apply a class conditionally based on a value:

In this example, the red class is applied if val is greater than 10; otherwise, the green class is applied.

Toggle Class Based on a Condition

To toggle a class based on a condition, you can use an object within ngClass:

Here, the error class is applied if control.isInvalid is true and removed if it's false.

Using [class.xxx] for Single Class

For applying a single class conditionally, you can use [class.xxx] syntax. It's ideal for simpler cases:

In this case, the error class is applied if control.isInvalid is true.

Complex Conditions under NgClass

Sometimes, you may require different class names based on multiple conditions. For instance, you might want to assign classes 'low,' 'medium,' or 'high' depending on the value of a variable. In JavaScript, you'd typically use an if/else statement. However, you can't directly use if/else in ngClass. Instead, you can define a function within your component to handle the logic and return the appropriate class name.

In the template, you can use [ngClass]="getClassOf(val)" to apply the class dynamically.

Avoiding Unnecessary Function Calls

While the above approach works, it's important to note that the getClassOf function might run multiple times due to Angular's ChangeDetection mechanism, even when it's unnecessary. Optimizing this is a more complex topic but worth considering.

Object Literal for Complex Conditions

An alternative to using a function is to employ an object literal. Although it may seem verbose, it offers better performance because it calculates the class name only once based on the conditions.

Transforming the Value First

To make your template cleaner and more readable, you can transform your val variable into a predefined class name within your component. This reduces the logic in the template.

In the template, you simply use [ngClass]="className" to apply the class dynamically.

Using Arrays or Objects for Mapping

If your class assignment is based on consecutive numbers or a simple mapping, you can use arrays or objects to define the relationships.

Example with an array:

In the template, you can apply the class using [ngClass]="classArr[val - 1]".

Example with an object:

In the template, you can apply the class using [ngClass]="classMap[val]".

NgClass Vs Class in Angular

FeaturengClassclass attribute
FunctionalityAllows dynamic binding of CSS classes based on expressions in the component.Provides static CSS class assignment.
Use CasesUseful when you need to conditionally apply CSS classes based on component data or logic.Suitable for applying static CSS classes to HTML elements.
SyntaxUses square brackets and accepts an expression as a value.Uses plain HTML syntax and requires a static class name.
Example Usage<div [**ngClass**]="{ 'active': isActive, 'disabled': isDisabled }"></div><div **class**="active"></div>
Multiple ClassesCan apply multiple classes based on conditions in an object.Can only apply a single, static class name.
Class BindingCan bind to a boolean expression, object, array, or string.Requires a string with the class name(s).
ExpressionsSupports complex expressions and computed class names.Supports simple, static class names.
Conditional ClassesIdeal for dynamically adding or removing classes based on component state.Suitable for cases where classes do not change.
FlexibilityOffers flexibility in managing CSS classes dynamically.Limited to static class assignment.

Conclusion

  • NgClass is a powerful Angular directive that allows for dynamic CSS class binding.
  • It enables you to conditionally add or remove CSS classes based on component data or expressions.
  • NgClass is versatile, as you can apply multiple classes simultaneously and toggle classes based on complex conditions.
  • It simplifies UI manipulation by eliminating the need for direct DOM manipulation in your components.
  • NgClass enhances code readability by centralizing class logic in your templates.
  • Useful for building responsive UIs by adapting styles based on user interactions or data changes.
  • NgClass seamlessly integrates with Angular's change detection mechanism, ensuring efficient updates to your UI.