When building modern web applications with Angular, dynamic styling plays a crucial role in improving user experience by allowing your app to respond visually to changes in state or data. One of the powerful tools Angular offers for dynamic styling is the ng-class
directive. This guide will walk you through how to implement ng-class
effectively to add dynamic CSS classes based on your component’s logic.
What is ng-class
?
ng-class
is an Angular directive that lets you dynamically set CSS classes on an HTML element. Unlike static class assignments, ng-class
updates the element’s class list based on an expression, enabling you to conditionally apply styles in response to your app’s state.
Why Use ng-class
?
- Simplifies dynamic styling: No need for cumbersome manual DOM manipulation.
- Keeps markup clean: You can manage classes through expressions rather than toggling classes imperatively.
- Improves maintainability: CSS and logic stay separated but work seamlessly to reflect UI changes.
- Enhances reactivity: Angular updates classes in response to changes automatically.
How to Implement ng-class
in Angular
1. Using an Object Expression
You can pass an object to ng-class
where the keys are CSS class names and the values are boolean expressions that Angular evaluates.
<div [ngClass]=”{ ‘active’: isActive, ‘disabled’: !isActive }”>
Click me!