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:
- The ng-class directive dynamically binds one or more CSS classes to an HTML element.
- The value of the ng-class directive can be a string, an object, or an array.
- If it is a string, it should contain one or more, space-separated class names.
- 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:
- <div ng-class="{class1 : expression1, class2 : expression2}">
-
- Hello World!
-
- </div >
Here class1 will apply if the expression1 is true and class2 will apply if the expression2 is true.
Ex 2:
- < div ng-class="{class1 : expression1, class2 : expression1}">
-
- Hello World!
-
- </div >
Here class1 and class2 will apply if the expression1 is true.
We can reduce the above code into,
- < div ng-class="{'class1 class2' : expression1}">
- Hello World!
-
- < /div >
Ex 3:
- < div data-ng-class="expression1 && 'class1' || 'class2'">
-
- Hello World!
-
- </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.