How to use ng-if and ng-class Directives In Angular

In this approach, we have conditionally applied the attributes and the styles using the “ng-if” and “ng-class” directives. Here in this example, the ng-if directive is used to dynamically add or remove the elements from the DOM based on the conditions. Also, this allows us to display an input field or edit a text when in edit mode. The “ng-class” directive is used to apply the CSS classes based on the values of specific item properties and mark the tasks completed or high-priority, etc. There is a user-defined function that is used to determine if the task’s due date is in the past. Overall, this approach is used to conditionally apply the attributes along with the styling of elements based on the conditions.

Example: Below is an example that demonstrates conditionally applying attributes in AngularJS using ng-if and ng-class.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
      </script>
    <style>
        .header {
            text-align: center;
        }
  
        .header h1 {
            font-size: 36px;
            color: green;
        }
  
        .item {
            margin: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            background-color: #f8f8f8;
            border-radius: 5px;
            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
        }
  
        .completed {
            background-color: #a5d6a7;
        }
  
        .high-priority {
            border: 2px solid #ff6347;
        }
  
        .overdue {
            background-color: #ff7f50;
        }
  
        .item h3 {
            font-size: 20px;
            margin: 0;
            padding: 0;
        }
  
        .item p {
            font-size: 16px;
            margin: 0;
            padding: 0;
        }
  
        .button-container {
            display: flex;
            justify-content: space-between;
        }
  
        .button-container button {
            background-color: #3498db;
            color: #fff;
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 5px;
        }
  
        .button-container button:hover {
            background-color: #2577a4;
        }
    </style>
</head>
  
<body ng-controller="MyController">
    <div class="header">
        <h1>w3wiki</h1>
        <h3>
              Approach 1: Using ng-if and ng-class
          </h3>
    </div>
    <div ng-repeat="item in items" 
         ng-class="{
            'completed': item.completed,
            'high-priority': item.priority,
            'overdue': isOverdue(item.dueDate)}">
        <div class="item">
            <h3>
                <span ng-if="!item.editing">
                      {{ item.title }}
                  </span>
                <input ng-if="item.editing" 
                       ng-model="item.title" 
                       ng-blur="saveTask(item)"
                       ng-keyup="$event.keyCode == 13 && saveTask(item)" />
            </h3>
            <p>
                  Status: 
                  {{ item.completed ? 'Completed' : 'Not Completed' }}
              </p>
            <p>
                  Due Date: {{ item.dueDate | date:'mediumDate' }}
              </p>
            <div class="button-container">
                <button ng-if="!item.completed" 
                        ng-click="toggleStatus(item)">
                      Complete
                  </button>
                <button ng-if="item.completed" 
                        ng-click="toggleStatus(item)">
                      Undo
                  </button>
                <button ng-click="editTask(item)">
                      Edit
                  </button>
            </div>
        </div>
    </div>
  
    <script>
        var app = angular.module('myApp', []);
        app.controller('MyController', function ($scope) {
            $scope.items = [
                { title: 'Task 1', 
                  completed: false,
                  priority: false, 
                  dueDate: new Date(2023, 10, 20), 
                  editing: false 
                },
                { title: 'Task 2', 
                  completed: true, 
                  priority: true, 
                  dueDate: new Date(2023, 10, 18), 
                  editing: false 
                },
                { title: 'Task 3', 
                  completed: false, 
                  priority: false, 
                  dueDate: new Date(2023, 10, 22), 
                  editing: false 
                },
            ];
            $scope.toggleStatus = function (item) {
                item.completed = !item.completed;
            };
            $scope.editTask = function (item) {
                item.editing = true;
            };
            $scope.saveTask = function (item) {
                item.editing = false;
            };
            $scope.isOverdue = function (dueDate) {
                const today = new Date();
                return dueDate < today;
            };
        });
    </script>
</body>
  
</html>


Output:

What is the best way to conditionally apply attributes in AngularJS?

In the AngularJS application, the best way to conditionally apply attributes to the elements mostly relies on the specific requirement and the actual nature of the attribute that we need to change. Mostly, considering the use cases, we can use the two common approaches for conditional attribute application by using the ng-if and ng-class directive and also the ng-disabled and ng-class to disable the elements conditionally. In this article, we will see both of the approaches with their implementation in terms of examples to conditionally apply attributes in AngularJS.

Similar Reads

Steps to Conditionally Apply Attributes in AngularJS

The below steps will be followed to conditionally apply attributes in AngularJS Applications....

Using ng-if and ng-class Directives

In this approach, we have conditionally applied the attributes and the styles using the “ng-if” and “ng-class” directives. Here in this example, the ng-if directive is used to dynamically add or remove the elements from the DOM based on the conditions. Also, this allows us to display an input field or edit a text when in edit mode. The “ng-class” directive is used to apply the CSS classes based on the values of specific item properties and mark the tasks completed or high-priority, etc. There is a user-defined function that is used to determine if the task’s due date is in the past. Overall, this approach is used to conditionally apply the attributes along with the styling of elements based on the conditions....

Using ng-disabled and ng-class Directives

...