Skip to main content

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:

  1. [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: ngClass lets you control styles through classes dynamically, without directly modifying the DOM or styles via Renderer2.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.