ngClass
ngClass
is a built-in directive in Angular that allows you to dynamically add or remove CSS classes to an HTML element based on an expression. This directive is particularly useful for changing the appearance of elements in response to component state or user interactions.
How ngClass
Works
ngClass
can be used in several ways, depending on the complexity of the conditions and the number of classes you need to manipulate. It evaluates the given expression and, based on its result, adds or removes CSS classes.
Basic Usage
Single Class Toggle: You can toggle a single class based on a truthy or falsy expression.
<div [ngClass]="{'active': isActive}">Content</div>
Here, the
active
class is added to the<div>
ifisActive
is truthy.Multiple Classes: You can toggle multiple classes using a similar object syntax.
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">Content</div>
This adds the
active
class ifisActive
is true and thedisabled
class ifisDisabled
is true.
Advanced Usage
Array Syntax: You can pass an array of class names, which will all be applied.
<div [ngClass]="[class1, class2, class3]">Content</div>
Here,
class1
,class2
, andclass3
are all added to the<div>
.Class with Conditional Logic: Using a function or a component property, you can return an object or array to
ngClass
.<div [ngClass]="getClassObject()">Content</div>
In the component:
getClassObject() {
return {
'class1': this.condition1,
'class2': this.condition2,
// more classes and conditions
};
}The function returns an object with class names as keys and conditionals as values.
Combining with Static Classes
ngClass
can be used alongside static class attributes. The static classes will always be applied, and the dynamic classes will be added or removed based on thengClass
expression.<div class="static-class" [ngClass]="{'dynamic-class': condition}">Content</div>
More examples
Here are more examples to illustrate its different applications:
Toggling Multiple Classes with an Object
Object Syntax for Multiple Conditions: Toggle multiple classes based on different conditions.
<div [ngClass]="{ 'class1': condition1, 'class2': condition2, 'class3': condition3 }">
Content
</div>This adds
class1
ifcondition1
is true,class2
ifcondition2
is true, and so on.
Using Component Properties
Based on Component Properties: Dynamically apply classes based on component property values.
<div [ngClass]="{ 'highlight': isHighlighted, 'shadow': hasShadow }">
Content
</div>Here,
isHighlighted
andhasShadow
are boolean properties in the component. The respective classes are applied based on their truthiness.
With Array Syntax
Array Syntax with Conditional Classes: Apply an array of classes, some of which are conditional.
<div [ngClass]="[ alwaysClass, condition ? 'conditionalClass' : '' ]">
Content
</div>alwaysClass
is always applied, whileconditionalClass
is applied only ifcondition
is true.
Combining Static and Dynamic Classes
Static and Dynamic Classes Together: Use
ngClass
alongside static class attributes.<div class="static-class" [ngClass]="{ 'dynamic-class': condition }">
Content
</div>The element always has
static-class
, anddynamic-class
is added based oncondition
.
Function Return Values
Using a Function to Determine Classes: Define a method in the component to return the classes.
<div [ngClass]="getClass()">Content</div>
In the component:
getClass() {
return {
'class1': this.condition1,
'class2': this.condition2,
// ... more logic
};
}This method returns an object with class names as keys and conditions as values.
Responsive Design
Responsive Styling: Apply different classes based on screen size or other environmental factors.
<div [ngClass]="{ 'mobile-class': isMobile, 'desktop-class': !isMobile }">
Content
</div>This applies
mobile-class
ifisMobile
is true (which could be determined by screen width), anddesktop-class
otherwise.
Form Validation Feedback
Form Validation Styles: Change styles based on the validation state of form controls.
<input [ngClass]="{ 'valid': myControl.valid, 'invalid': myControl.invalid }" type="text" formControlName="myControl">
This applies
valid
orinvalid
classes based on the control's validation status.
Dynamic Theme Application
Dynamic Theming: Apply a theme class based on a user's preference or setting.
<div [ngClass]="currentTheme">Content</div>
currentTheme
is a string property in the component that holds the name of the CSS class representing the theme.
Toggle Classes with User Interaction
Toggling Classes on Events: Change classes in response to user actions like click, hover, etc.
<div (click)="toggleClass = !toggleClass" [ngClass]="{ 'active': toggleClass }">
Click me
</div>Toggles the
active
class on click.
Use Cases
- Styling Based on Component State: Changing the appearance of elements based on the state of the component (e.g., active/inactive states, validation states in forms).
- Responsive Design: Applying different styles based on screen size or other environmental factors.
- User Interactions: Changing styles in response to user actions like hover, click, etc.
Best Practices
- Keep It Simple: Avoid overly complex expressions in
ngClass
. If the logic gets complicated, consider moving it to the component class. - Performance Considerations: Be mindful of performance, especially when using functions or methods that return class objects or arrays, as they can be called frequently.
Conclusion
ngClass
is a powerful and flexible directive for dynamically manipulating CSS classes of elements in Angular applications. It enhances the ability to create responsive and interactive user interfaces by binding element class attributes to component logic. Understanding ngClass
and its various usage patterns is essential for effective Angular development.