Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
ngClass in Angular is a directive that allows developers to dynamically assign CSS classes to an element based on certain conditions. This feature makes it easy to style elements based on the application’s state or user actions. With ngClass, you can apply or remove multiple classes efficiently without hardcoding them in the HTML.
This article will discuss the concept of ngClass, its syntax, and how to use it effectively with examples.
What is ngClass in Angular? The Basics
ngClass is a built-in Angular directive that allows you to conditionally apply one or more CSS classes to an HTML element. It is particularly useful for dynamic styling based on application state or user interactions. With ngClass, you can easily manage classes using expressions, arrays, or objects.
When you click the button, the text's styles will toggle between the active and highlight classes.
How to Use Angular ngClass with a Simple Condition
`ngClass` is a directive in Angular that helps you dynamically apply CSS classes to HTML elements based on certain conditions. It’s especially useful when you want to change the appearance of an element depending on the state of your application. Let’s understand this with a simple example.
Basic Syntax of `ngClass`
The `ngClass` directive can be used in two ways:
1. Object Syntax: Here, you pass an object where the keys are the class names & the values are conditions. If the condition is `true`, the class is applied.
2. Array Syntax: You can also pass an array of class names, which will be applied unconditionally.
Example: Using `ngClass` with a Simple Condition
Let’s say you have a button, & you want to apply a CSS class called `active` when a variable `isActive` is `true`. Let’s see how you can do it:
1. Step 1: Set Up Your Angular Component
First, create a new Angular component or use an existing one. In your component’s TypeScript file (`app.component.ts`), define a variable `isActive`:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isActive: boolean = true; // You can change this value to false to see the difference
}
2. Step 2: Add CSS Classes
In your component’s CSS file (`app.component.css`), define the `active` class:
Here, `{ 'active': isActive }` is an object where `active` is the class name, & `isActive` is the condition. If `isActive` is `true`, the `active` class will be applied to the button.
4. Step 4: Test the Output
Run your Angular application using `ng serve`. If `isActive` is `true`, the button will have a green background & white text. If you change `isActive` to `false`, the button will revert to its default style.
In this Code:
- The `ngClass` directive is used inside square brackets (`[]`) because it’s a property binding.
- The object `{ 'active': isActive }` tells Angular to apply the `active` class only if `isActive` is `true`.
- This approach is clean & easy to understand, making it perfect for simple conditions.
Angular ngClass and Complex Conditions
While `ngClass` is great for simple conditions, it truly shines when dealing with more complex scenarios. You can use multiple conditions, logical operators, & even functions to determine which classes should be applied. Let’s explore this with an example.
Example: Using `ngClass` with Multiple Conditions
Suppose you have a user interface where you want to apply different styles to a button based on two conditions:
1. Whether the button is active (`isActive`).
2. Whether the button is disabled (`isDisabled`).
Let’s see how you can achieve this:
1. Step 1: Set Up Your Angular Component
In your component’s TypeScript file (`app.component.ts`), define the variables `isActive` & `isDisabled`:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isActive: boolean = true; // Change this to test
isDisabled: boolean = false; // Change this to test
}
2. Step 2: Add CSS Classes
In your component’s CSS file (`app.component.css`), define the classes for different states:
- If `isActive` is `true` & `isDisabled` is `false`, the `active` class is applied.
- If `isDisabled` is `true`, the `disabled` class is applied.
- If neither `isActive` nor `isDisabled` is `true`, the `default` class is applied.
4. Step 4: Test the Output
Run your Angular application using `ng serve`. Try changing the values of `isActive` & `isDisabled` in the component file to see how the button’s appearance changes.
In this Code:
- The `ngClass` directive now uses an object with multiple key-value pairs. Each key is a class name, & the value is a condition.
- Logical operators like `&&` (AND) & `!` (NOT) are used to create complex conditions.
- This approach allows you to handle multiple states & apply different styles dynamically.
Conditional Class with *ngClass
The *ngClass directive provides a clean way to conditionally apply classes based on component state.
The selected class will be applied only to items where item.selected is true.
Approach 1: Using Boolean Properties
This approach uses Boolean variables to control class application.
Example
<button [ngClass]="{'btn-primary': isPrimary, 'btn-secondary': !isPrimary}">
Click Me
</button>
In the component:
isPrimary: boolean = true;
Output:
The button will have the btn-primary class if isPrimary is true, otherwise btn-secondary.
Approach 2: Using Functions
Another approach is to use functions to return the desired class names.
Example
<div [ngClass]="getClassNames()">
Dynamic Classes
</div>
In the component:
getClassNames() {
return {
'class-a': this.conditionA,
'class-b': this.conditionB
};
}
Output:
The classes class-a and class-b will be applied based on the return values of conditionA and condition.
[ngClass] vs [class] in Angular
Feature
[ngClass]
[class]
Purpose
Dynamically add or remove CSS classes based on conditions. Binds class names to expressions or object literals.
Statically apply CSS classes to an element. Binds a fixed set of classes to the element.
Syntax
[ngClass]="{'class-name': condition}" or [ngClass]="expression"
[class]="'class-name'" or [class.class-name]="condition"
Dynamic Binding
Supports dynamic binding of classes based on conditions or expressions. Classes can be added or removed dynamically at runtime.
Supports static binding of classes. Classes are fixed and cannot be dynamically changed.
Multiple Classes
Allows applying multiple classes using key-value pairs in an object literal or an array of class names.
Allows applying multiple classes by specifying them as a space-separated string.
Conditional Classes
Suitable for applying classes conditionally based on component logic or user interactions. Uses boolean expressions, object literals, or functions.
Suitable for applying classes unconditionally. Conditional application uses [class.class-name]="condition" syntax.
Readability
Can be less readable with complex conditions or multiple classes, making the template more verbose.
More readable for applying fixed classes. Clearly shows class names in the template.
Performance
Slight performance overhead due to dynamic evaluations. Negligible impact unless dealing with many elements.
Better performance as it applies classes statically without dynamic evaluations.
Frequently Asked Questions
What is ngClass used for?
ngClass is used to dynamically add or remove CSS classes on an HTML element based on component logic.
Can I apply multiple classes using ngClass?
Yes, you can apply multiple classes using object, array, or string syntax.
What is the difference between [ngClass] and class binding?
class binding is used for a single class, while ngClass is used for conditional and multiple class bindings.
Conclusion
In this article, we explored the ngClass directive in Angular, which is an essential tool for dynamic class manipulation. From its syntax to various approaches, we learned how to apply conditional styling effectively. Mastering ngClass will help you build more interactive and user-friendly applications.