ng-class
Description
The ng-class directive allows dynamically setting CSS classes on an HTML
element by binding to an expression. The directive supports the following
expression types:
- String — space-delimited class names.
- Object — keys as class names and values as booleans. Truthy values add the class.
- Array — containing strings and/or objects as described above.
When the expression changes:
- Previously added classes are removed.
- New classes are added.
- Duplicate classes are avoided.
Important: Avoid using interpolation ({{ ... }}) in the value of the
class attribute together with ng-class. See
interpolation known issues for
details.
Animations
If data-animate attribute is present, the following animations will be applied
to the element:
| Animation | Occurs |
|---|---|
add-class | Before the class is applied to the element |
remove-class | Before the class is removed from the element |
set-class | Before classes are simultaneously added and removed |
ng-classsupports standard CSS3 transitions/animations even if they don’t follow$animateservice naming conventions.
Parameters
ng-class
Type:
string | object | arrayDescription: An expression whose result determines the CSS classes to apply.
Example:
<div ng-class="{ active: isActive, disabled: isDisabled }"></div>
Demo
<style>
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold !important;
}
.red {
color: red;
}
.has-error {
color: red;
background-color: yellow;
}
.orange {
color: orange;
}
</style>
<section ng-app>
<p ng-class="{strike: deleted, bold: important, 'has-error': error}">
Map Syntax Example
</p>
<label>
<input type="checkbox" ng-model="deleted" />deleted (apply "strike" class)
</label>
<br />
<label>
<input type="checkbox" ng-model="important" />important (apply "bold" class)
</label>
<br />
<label>
<input type="checkbox" ng-model="error" />error (apply "has-error" class)
</label>
<hr />
<p ng-class="style">Using String Syntax</p>
<input
type="text"
ng-model="style"
placeholder="Type: bold strike red"
aria-label="Type: bold strike red"
/>
<hr />
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input
ng-model="style1"
placeholder="Type: bold, strike or red"
aria-label="Type: bold, strike or red"
/><br />
<input
ng-model="style2"
placeholder="Type: bold, strike or red"
aria-label="Type: bold, strike or red 2"
/><br />
<input
ng-model="style3"
placeholder="Type: bold, strike or red"
aria-label="Type: bold, strike or red 3"
/><br />
<hr />
<p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
<input
ng-model="style4"
placeholder="Type: bold, strike"
aria-label="Type: bold, strike"
/>
<br />
<label
><input type="checkbox" ng-model="warning" /> warning (apply "orange"
class)</label
>
</section>
Map Syntax Example
Using String Syntax
Using Array Syntax
Using Array and Map Syntax
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.