[email protected]      beta

AngularJs ng-class directives

Overview: Understanding ng-class directive, Use of AngularJS ng-class directives with an example, with ng-class bind one or more CSS classes to an HTML element, Different ways of using ng-class.

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.

  1. 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.
  2. 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.
  3. 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> 

Try is yourself


Example of using ng-class directive, and adding classes dynamically

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> 

Try is yourself

  Popular Tag
  Recent Posts
  Follow Us
If you find these tutorials helpful then please donate. It will lead me to do more tutorials.