Ng-class in AngularJS

AngularJS help us create interactive applications. They provide things called directives in order to change the DOM and attach specific Angular behaviors to an element we specify.

ngClass directive : This directive lets us do things like,

  • Add/Remove classes based on Angular variables.
  • Add/Remove classes based on evaluated expressions.
  • Bind single or multiple classes based on dynamic data.

Some Points about ng-class:

  1. The ng-class directive dynamically binds one or more CSS classes to an HTML element.

  2. The value of the ng-class directive can be a string, an object, or an array.

  3. If it is a string, it should contain one or more, space-separated class names.

  4. As an object, it should contain key-value pairs, where the key is a Boolean value, and the value is the class name of the class you want to add. The class will only be added if the key is set to true.

Examples

Ex 1:

  1. <div ng-class="{class1 : expression1, class2 : expression2}">  
  2.   
  3. Hello World!  
  4.   
  5. </div >   

Here class1 will apply if the expression1 is true and class2 will apply if the expression2 is true.

Ex 2:

  1. < div ng-class="{class1 : expression1, class2 : expression1}">  
  2.   
  3. Hello World!  
  4.   
  5. </div >   

Here class1 and class2 will apply if the expression1 is true.

We can reduce the above code into,

  1. < div ng-class="{'class1 class2' : expression1}">  
  2. Hello World!  
  3.   
  4. < /div >  

Ex 3:

  1. < div data-ng-class="expression1 && 'class1' || 'class2'">  
  2.   
  3. Hello World!  
  4.   
  5. </div >   

Here class1 will apply if the expression1 is true, otherwise class2 will apply.

This was a look at how you can use the useful ngClass directive in many different ways.