ng-class directive is used to dynamically set one or more CSS classes to an HTML element.
ng-class directive value can be a string, an object, or an array.
If the value of the ng-class directive is string, it should contain one or more, space-separated class names.
If the value of the ng-class directive is an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value.
If the value of the ng-class directive is an array, each array element can be either a string, or an object, described as above.
All HTML elements supported the ng-class directive.
The directive will not add duplicate classes if a particular class was already existing.
Syntax for ng-class directive in AngularJS:
Parameter value for ng-class directive in AngularJS:
It is used to define an expression that returns one or more class names.
Sample coding for ng-class directive in AngularJS:
Code Explanation for ng-class directive in AngularJS:
AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
.blue {color : blue;} is used to define a CSS class as blue which is used to set the <div> element’s font-color as blue.
.font {font-size: 20px;} is used to define a CSS class as font which is used to set the <div> element’s font-size as 20px.
. orange {background-color: orange;} is used to define a CSS class as orange which is used to set the <div> element’s background color as orange.
The AngularJS application is defined by ng-app=" ". The application runs inside the <body> tag. It’s also used to define a <body> tag as a root element.
The <input> tag is used to define the checkbox and the ng-model is used to bind the fontsize when the user click this checkbox.
The <input> tag is used to define the checkbox and the ng-model is used to bind the bluecolor when the user click this checkbox.
The <input> tag is used to define the checkbox and the ng-model is used to bind the orangecolor background when the user click this checkbox.
<div ng-class="{blue: bluecolor, font: fontsize , orange: orangecolor }"> here the ng-class directive is used to dynamically set three CSS classes to a <div> tag.
Sample Output for ng-class directive in AngularJS:
The output displays the checkbox and content when the page was loaded.
The content “Wikitechy ng-class Directive in AngularJS!” font-size is changed as 20 pixels when the checkbox name as Font Size is clicked.
The content “Wikitechy ng-class Directive in AngularJS!” font-size is changed as 20 pixels and font color is changed as blue when the checkbox both name as Font Size and Blue Color are clicked.
The content “Wikitechy ng-class Directive in AngularJS!” font-size is changed as 20 pixels; font color is changed as blue and background color is changed as orange when the user clicked three checkboxes.