Conditionally class apply on any element in Angular JS

In Angular JS, We can set classes on HTML element dynamically.

For this, we need to use ng-class with expression:

Syntax:

  <div class="ng-class: expression ;"> ...</div>

Suppose, If we want add specific class on any element on different condition, Then its easy to add in Angular JS.

Example 1:

If we want add a class if expression is true.

  ng-class="{ 'myclass': obj.isColor == true }"

If value of obj.isColor is true then it will add ‘myclass’ on element.

If value of obj.isColor is other than true then it will not add anything on element.

 

Example 2:

Now I have 3 roles in my app and i want show a specific label color on a element based on role.

If role is admin then use blue class and  moderator then use grey class and user then use red class.

admin => ‘blue’
moderator => ‘grey’
user => ‘red’

   ng-class="{admin: 'blue', moderator:'grey', user:'red'} [role]"

Here role is angular scope and it may contains ‘admin’, ‘moderator’ and ‘user’.

if role is admin then it will add blue class on element.

 

According to Angular JS DOCS:

  The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
  The directive operates in three different ways, depending on which of three types the expression evaluates to:
  If the expression evaluates to a string, the string should be one or more space-delimited class names.
  If the expression evaluates to an array, each element of the array should be a string that is one or more space-delimited class names.
  If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name.
  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.

 

For More Info see this:  https://docs.angularjs.org/api/ng/directive/ngClass