- Angular class binding is used to add or remove CSS classes on HTML elements dynamically.
- It allows you to conditionally apply CSS classes, enabling elements to be styled based on component properties or expressions.
- Angular provides three ways to add or remove classes:
- Using the DOM
className
property (direct manipulation). Here dynamic class binding (using [class]
).
- Using class binding shorthand with
[class.className]="condition"
. Shorthand for class binding can also be used with conditions.
- Using the
ngClass
directive for more complex class manipulations. Here we introduce ngClass
for more complex scenarios.
1. Example: Using Class Binding (Shorthand)
<!-- app.component.html -->
<div [class.active]="isActive">This div will have 'active' class if isActive is true</div>
2. Example: Using ngClass
Directive
<!-- app.component.html -->
<div [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">This div has 'active' and 'disabled' classes</div>
2. Using DOM className
Property (Direct Manipulation)
<!-- app.component.html -->
<div [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">This div has 'active' and 'disabled' classes</div>