ng-class – Applying CSS classes dynamically

Loading

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:

  1. What is ng-class?
  2. Basic Syntax
  3. Using ng-class with Expressions
  4. Using ng-class with Objects
  5. Using ng-class with Arrays
  6. Conditional Styling with ng-class
  7. Example: Highlighting Active Items
  8. Example: Changing Button Colors Dynamically
  9. Performance Considerations
  10. Best Practices
  11. 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 the my-class CSS 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.role is 'admin', the paragraph gets the admin-style class.
  • Otherwise, it gets the user-style class.

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 class active is applied.
  • If isDisabled = true, the class disabled is 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 isActive and isDisabled, 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, the primary class is applied.
  • If isError = true, the error class 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, the highlight class 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 selected class 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-class is efficient but avoid complex expressions inside it.
  • Use objects instead of inline conditions for better readability.
  • Avoid frequent DOM manipulations inside ng-class when handling large lists.

Leave a Reply

Your email address will not be published. Required fields are marked *