← Back to Chapters

Dynamic Styling & Class Binding

? Dynamic Styling & Class Binding

Angular Templates [style] • [class] • ngClass

? Quick Overview

Angular lets you change CSS styles and classes dynamically from your component. You can use [style] bindings for inline styles and [class] or [ngClass] for class-based styling. This makes your UI react to component state (variables, conditions, events) in real time.

? Key Concepts

  • Dynamic style binding with [style.property] or the shorthand [style].
  • Class binding with [class.className] to toggle a single CSS class.
  • [ngClass] to apply multiple classes using an object, array, or string.
  • Component properties (like isActive, fontSize) directly control how the element looks.
  • Prefer CSS classes for reusable styling; use inline [style] for conditional one-off changes.

? Syntax & Theory

  • Inline style binding:
    [style.color]="isActive ? 'green' : 'red'"
    [style.fontSize.px]="fontSize"
  • Single class binding:
    [class.highlight]="isHighlighted"
  • Multiple classes with object:
    [ngClass]="{ highlight: isHighlighted, warning: isWarning }"
  • Multiple classes with array:
    [ngClass]="['highlight', dynamicClass]"

? Dynamic Style Binding Example

? View Code Example
// app.component.ts - dynamic style binding
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  isActive = true;
  fontSize = 20;
}
? View Template Example
// app.component.html - dynamic inline styles
<p
  [style.color]="isActive ? 'green' : 'red'"
  [style.fontSize.px]="fontSize"
>
  Dynamic styled text
</p>

? Live Output / Explanation

When isActive is true, the text appears in green; when it is false, it appears in red. The fontSize property controls the font size in pixels through [style.fontSize.px].

Changing isActive or fontSize in the component (e.g., on button click or slider change) immediately updates the element styles in the template.

? Class Binding Example

? View Code Example
// app.component.ts - class binding
export class AppComponent {
  isHighlighted = true;
  isWarning = false;
}
? View Template Example
// app.component.html - single class binding
<p [class.highlight]="isHighlighted">This is highlighted</p>
<p [class.warning]="isWarning">This is a warning</p>

? What Happens?

The highlight class is added to the first paragraph only when isHighlighted is true. Similarly, the warning class is added to the second paragraph when isWarning is true.

This is great for toggling a single class based on a boolean condition, such as active state, error, or success.

? Using ngClass for Multiple Classes

? View Object-Based ngClass Example
// app.component.ts - ngClass with object
export class AppComponent {
  classes = {
    highlight: true,
    warning: false
  };
}
? View Template Example
// app.component.html - multiple classes with ngClass
<p [ngClass]="classes">This text uses ngClass</p>
? View Advanced ngClass Example
// app.component.ts - ngClass with method
export class AppComponent {
  isHighlighted = true;
  isWarning = true;

  getClasses() {
    return {
      highlight: this.isHighlighted,
      warning: this.isWarning
    };
  }
}
? View Template with Method
// app.component.html - bind to getClasses()
<p [ngClass]="getClasses()">
  This text can be both highlighted and warning
</p>

? Explanation

With [ngClass], you can:

  • Use an object where keys are class names and values are booleans.
  • Use a method like getClasses() to compute classes dynamically.
  • Apply multiple classes at the same time based on conditions.

? Common Use Cases

  • Highlighting the currently selected menu item.
  • Showing success, warning, or error states with different colors.
  • Changing card styles on hover or on selection.
  • Applying responsive classes (e.g., small vs. large layout) based on device or user choice.

✅ Tips & Best Practices

  • Use [style] for simple, dynamic styles like color, width, and font size.
  • Prefer [class] when toggling a single CSS class based on a boolean.
  • Use [ngClass] for multiple classes or when logic gets more complex.
  • Keep most styling in stylesheets; use dynamic styling only when it depends on component state.
  • Avoid putting heavy logic directly inside templates; move it into component methods if needed.

? Try It Yourself

  • Create a button that toggles a paragraph's color between green and red using [style.color] and a boolean property.
  • Bind a range (slider) input to fontSize and use [style.fontSize.px] to dynamically resize a paragraph.
  • Define highlight and warning classes in your CSS and use [ngClass] to apply one or both based on component properties.
  • Build a simple navigation bar where the active link uses [class.active] for styling.