![]()
ng-class is an AngularJS directive used to dynamically assign CSS classes to elements based on conditions or expressions. Instead of manually toggling classes using JavaScript, ng-class allows you to manage class assignments efficiently within templates.
Topics Covered:
- What is
ng-class? - Basic Syntax
- Using
ng-classwith Expressions - Using
ng-classwith Objects - Using
ng-classwith Arrays - Conditional Styling with
ng-class - Example: Highlighting Active Items
- Example: Changing Button Colors Dynamically
- Performance Considerations
- Best Practices
- Conclusion
1. What is ng-class?
ng-class dynamically adds or removes CSS classes based on conditions.
It can be used with expressions, objects, or arrays to apply multiple classes.
Helps maintain cleaner and more maintainable templates.
2. Basic Syntax
<div ng-class="{'my-class': condition}">
This element gets the class "my-class" when condition is true.
</div>
- If
condition = true, the element gets themy-classCSS class. - If
condition = false, the class is not applied.
3. Using ng-class with Expressions
You can use ng-class to apply a class based on an expression:
<p ng-class="user.role == 'admin' ? 'admin-style' : 'user-style'">User Role</p>
- If
user.roleis'admin', the paragraph gets theadmin-styleclass. - Otherwise, it gets the
user-styleclass.
4. Using ng-class with Objects
You can pass an object where keys are class names and values are Boolean conditions:
<div ng-class="{'active': isActive, 'disabled': isDisabled}">
Dynamic Styling Example
</div>
- If
isActive = true, the classactiveis applied. - If
isDisabled = true, the classdisabledis applied.
Example with Controller:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ng-class Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<style>
.active { color: green; font-weight: bold; }
.disabled { color: gray; }
</style>
</head>
<body ng-app="myApp" ng-controller="MainController">
<button ng-click="toggleState()">Toggle State</button>
<p ng-class="{'active': isActive, 'disabled': isDisabled}">
This text changes color based on the state.
</p>
<script>
var app = angular.module("myApp", []);
app.controller("MainController", function($scope) {
$scope.isActive = true;
$scope.isDisabled = false;
$scope.toggleState = function() {
$scope.isActive = !$scope.isActive;
$scope.isDisabled = !$scope.isDisabled;
};
});
</script>
</body>
</html>
Explanation:
- Clicking the button toggles
isActiveandisDisabled, switching the styles.
5. Using ng-class with Arrays
You can use an array to apply multiple classes:
<div ng-class="['class1', 'class2']">
This element has multiple classes.
</div>
You can also mix expressions inside an array:
<div ng-class="[isPrimary ? 'primary' : '', isError ? 'error' : '']">
Conditional Multiple Classes
</div>
- If
isPrimary = true, theprimaryclass is applied. - If
isError = true, theerrorclass is applied.
6. Conditional Styling with ng-class
<input type="text" ng-model="userInput">
<p ng-class="{'highlight': userInput.length > 5}">
This text is highlighted if the input has more than 5 characters.
</p>
- If
userInput.length > 5, thehighlightclass is applied.
7. Example: Highlighting Active Items
<ul>
<li ng-repeat="item in items"
ng-click="selectedItem = item"
ng-class="{'selected': selectedItem === item}">
{{ item }}
</li>
</ul>
- Clicking an item applies the
selectedclass to it.
8. Example: Changing Button Colors Dynamically
<button ng-class="{'btn-success': isApproved, 'btn-danger': !isApproved}"
ng-click="toggleStatus()">
{{ isApproved ? 'Approved' : 'Not Approved' }}
</button>
jsCopyEdit$scope.isApproved = false;
$scope.toggleStatus = function() {
$scope.isApproved = !$scope.isApproved;
};
- The button toggles between green (
btn-success) and red (btn-danger) when clicked.
9. Performance Considerations
ng-classis efficient but avoid complex expressions inside it.- Use objects instead of inline conditions for better readability.
- Avoid frequent DOM manipulations inside
ng-classwhen handling large lists.
