What is ng-class directives in Angularjs ?
In angularjs with
ng-class directive, we can dynamically add or remove CSS class to the HTML element, also based on some condition. We can add one or more CSS classes at a time using ng-class directive. We can add/ remove CSS classes based on an angular variable, based on expressions, and based on dynamic data.
The ng-class directive values can be a string value, an object or an array.
- String: If it is string value it should have at least one class name, and for adding multiple class we can add space between each class name.
- Object: If it is an object, it needs to be the Key-Value pair, where the key represents the class name and value is the boolean value. I.e., if the boolean value set to true, then only the class gets added.
- Array: If it is an array, it can be a combination of both String and Object
Example 1: using ng-class with string value.
Here we added a textbox and a div tag. Whatever value entered inside the Textbox, get set as class to our DIV tag
Enter ClassName <input type="text" ng-model="className"><br/> <div ng-class="className">Hello World! </div>
Example 2: using ng-class with array.
Here we have two textboxes, each textbox values gets added to our DIV tag.
Enter class one:<input type="text" ng-model="classOne"> Enter class two:<input type="text" ng-model="classTwo"> <div ng-class="[classOne, classTwo]">Hello world!</div>