0
0
AngularHow-ToBeginner · 4 min read

How to Use ngClass in Angular: Syntax and Examples

Use ngClass in Angular to add or remove CSS classes dynamically by binding it to a string, array, or object. It updates the element's classes based on the expression's value, allowing conditional styling easily.
📐

Syntax

The ngClass directive can be used in three main ways:

  • String: A space-separated string of class names.
  • Array: An array of class names.
  • Object: An object where keys are class names and values are booleans indicating whether to apply the class.
html
<div [ngClass]="'class1 class2'">String syntax</div>
<div [ngClass]="['class1', 'class2']">Array syntax</div>
<div [ngClass]="{ 'class1': condition1, 'class2': condition2 }">Object syntax</div>
💻

Example

This example shows how to toggle CSS classes based on a component property using ngClass. The button toggles the active class on the text.

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-ngclass-example',
  template: `
    <p [ngClass]="{ active: isActive, disabled: !isActive }">This text changes style.</p>
    <button (click)="toggle()">Toggle Active</button>
  `,
  styles: [
    `p { font-size: 1.2rem; }`,
    `.active { color: green; font-weight: bold; }`,
    `.disabled { color: gray; font-style: italic; }`
  ]
})
export class NgClassExampleComponent {
  isActive = false;

  toggle() {
    this.isActive = !this.isActive;
  }
}
Output
Initially, the paragraph text appears gray and italic. Clicking the button toggles the text color to green and bold, or back to gray and italic.
⚠️

Common Pitfalls

Common mistakes when using ngClass include:

  • Using ngClass without square brackets, which disables binding.
  • Passing a non-boolean value in the object syntax, which may not toggle classes correctly.
  • Forgetting to update the bound property, so classes don't change dynamically.
html
<!-- Wrong: missing binding brackets -->
<div ngClass="active">This will not toggle dynamically</div>

<!-- Right: with binding -->
<div [ngClass]="{ active: isActive }">This toggles based on isActive</div>
📊

Quick Reference

Use these tips to remember ngClass usage:

  • Use square brackets [] for binding.
  • Pass a string, array, or object to ngClass.
  • Use object syntax for conditional classes.
  • Update component properties to change classes dynamically.

Key Takeaways

Use ngClass with binding brackets to dynamically add or remove CSS classes.
You can pass a string, array, or object to ngClass for flexible styling.
Object syntax lets you toggle classes based on boolean conditions.
Always update the bound properties in your component to reflect class changes.
Avoid missing brackets or incorrect value types to prevent ngClass from not working.