The ng-class is an inbuilt directive of angularJS that allows users to dynamically bind css class to html element based on some condition.
The defined css class will be automatically assigned to elements whenever condition becomes true and also removed if condition becomes false.
So the user has not to worry about adding /removing the css class again once,based on the condition that the resulting class will be added and removed.
Here the condition can be any type i.e on object value, array, number,string etc and based on the condition expression’s resultI(boolean) the class will be added and removed.
Syntax:
Example:
Css:
.highlight { border:2px solid red; color:blue }
Here the div will have css class highlight assigned as the condition is true.
If we change the html to…
Then the highlight class will not be assigned to div as the condition result is false.
So we can see here using ng-class we can add css class to html elements conditionally
Scenario:
An example to show a list of people for selection, and on selection of any person name from the selection list, the Title and information text style will be updated with ng-class directive…
HTML:
AngularJS ng-class Example
I will be highlighted if any person from dropdown gets selected by userPerson name
Example:
This is shorthand syntax for scenarios when we want to add multiple classes on elements based on the same condition.
if we don’t use above shorthand syntax then we have to write code like: