Explain Codes LogoExplain Codes Logo

Angular: conditional class with *ngClass

javascript
angular
class-binding
conditional-class
Anton ShumikhinbyAnton Shumikhin·Jan 29, 2025
TLDR

In Angular, one can easily toggle classes using [ngClass]. It can be done based on the conditional expressions as follows:

<div [ngClass]="{'text-bold': isBold, 'text-italic': isItalic}"> <!-- Your whims and fancies here, toggled in style --> </div>

Variables isBold and isItalic control our theatrical classes 'text-bold' and 'text-italic'. Make them true or false as your heart desires, and the magic of Angular does the rest!

When it comes to single class toggles, behold the power of [class.class-name]="condition":

<div [class.text-highlight]="isHighlighted"> <!-- Your content suddenly glows when isHighlighted sees the light of truth! --> </div>

Class Binding Fu

Why settle for one when you can have an array? Bind multiple classes based on a variety of conditions using a singular, almighty [ngClass] directive:

<div [ngClass]="{'text-bold': isBold, 'text-italic': isItalic, 'text-underline': isUnderlined}"> <!-- Your content now can go into 007 stealth mode or full drama queen, and anywhere in between --> </div>

This is a DRY method, like the gin in your martini. Your code stays readable, the environment stays friendly, and your elements stay flexibly fabulous.

Your Steps have Class

Want your classes to strut on the app's state like a runway model? Map an object with step keys to class values in [ngClass]:

<div [ngClass]="{1: 'first-class', 2: 'second-class', 3: 'third-class'}[currentStep]"> <!-- Content styled according to the current step, walks down the memory lane, and struts down the virtual runway --> </div>

As the spotlight shifts on your currentStep variable, and your spectators (classes) follow suit in a delightful spectacle of automatic toggling.

Trickier Turns and Twisty Turns

Beware of the seemingly innocuous [class]="expression" syntax. It plays a cruel trick and replaces all classes on the element. The horror! Super specific [class.class-name]="condition" or [ngClass] toggle specific classes:

<!-- ❌ This is where happiness goes to die. Just for the brave and foolish (or learn the hard way) --> <div [class]="isSpecial ? 'special-class' : ''"> <!-- All classes vanish! Vous ne passerez pas, Gandalf style! --> </div>

Friend or Foe: Built-in Directives vs Manual Class Management

Manual class manipulation in TypeScript could be cool if it was Doctor Strange's time stone. But alas! It sparks side-effect fireworks and is considered very un-Angular. Always stay in Angular's good books by using [ngClass] or [class.class-name].

From simply complex to complexly simple

Life is like [ngClass], full of hurdles and joys. Some hurdles you might stumble upon:

  • Type errors: Angular needs a truthy or falsy value. It can't work with Schrodinger's cat (an undefined variable).
  • Ternary operations: [ngClass]="condition ? 'class1' : 'class2'" makes a blink-and-miss appearance but bows out politely when faced with multiple class conditions. Classy indeed!
  • Class precedence: It's a dog eat dog world out there. The last one takes the crown. Makes for a thrilling survival of the fittest watch!

Tools of the trade

  • Reactivity: Bind [ngClass] to a getter function. Angular can keep up with state changes.
  • Direct DOM manipulation: As alluring as it seems, it's a siren call leading to bugs and blues! Stick with Angular.
  • ngStyle as wingman: Conditional styling needs a partner in crime. And [ngStyle] could be your Robin hood!