What does ngClass do?
The [ngClass] directive in Angular is an attribute directive that lets you dynamically add or remove CSS classes on an element based on expressions or conditions.
How it works:
[ngClass]accepts a string, an array or an object:
- String: one or more class names separated by spaces.
- Array: a list of classes.
- Object: key - the class name, value - a boolean expression.
Examples:
html
<!-- String -->
<div [ngClass]="'class1 class2'">Text</div>
<!-- Array -->
<div [ngClass]="['class1', 'class2']">Text</div>
<!-- Object -->
<div [ngClass]="{'active': isActive, 'highlight': isHighlighted}">
Text
</div>Conclusion:
ngClasslets you control styles through classes dynamically, without directly modifying the DOM or styles viaRenderer2.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.