Conditionally apply a class with AngularJS

Using AngularJs we can apply a class condionally on any element by using ng-class.

According to AngularJS docs on ng-class

The ng-class allows you to dynamically set a css class name on html element by data-binding an expression that represents all classes to be added.


ng-class supports an expression that must evaluate to either
  1. a string of space-delimited class names, or
  2. an array of class names, or
  3. a map/object of class names to boolean values.

Example:

Consider you have a div element as shown below

<div class="example">
    //inner elements
</div>

Now if you want to add class named "selected" to the above div conditionally. You can add the class using below code

<div class="example" ng-class="{'selected':isActive}">
    //inner elements
</div>

The class named "selected" gets applied to the above div only if "isActive" property is true.

The result will be like below

<div class="example selected" ng-class="{'selected':isActive}">
    // inner elements
</div>

You can even directly add a property(of model) as a class. see code below

<div ng-class="model.color">
    //inner elements
</div>

if model.color is "red" class named "red" is gets applied to the div.

The result will be like below

<div class="red" ng-class="model.color">
    //inner elements
</div>

Note

The directive won't add duplicate classes if a particular class was already set.
When the expression changes, the previously added classes are removed and only then the new classes are added.

In this way you can apply a class conditionally using AngularJS


For more posts on AngularJS please visit : AngularJS

1 comment:

  1. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it. The angular js programming language is very popular which are most widely used.
    AngularJS Training in Chennai | Angularjs training Chennai

    ReplyDelete