Reader Stacks

Dynamically Applying CSS Styles and Classes in Angular

ngClass suits toggling named classes on and off; ngStyle suits computed inline values — reaching for the wrong one just means fighting the syntax for a job the other directive already handles cleanly.

Angular's [ngClass] and [ngStyle] directives both let a template's appearance respond to component state, but they solve genuinely different problems — ngClass for toggling predefined named classes, ngStyle for computed inline style values.

ngStyle with a simple object

Dynamic text
textColor = 'blue';
fontSize = 16;

The 'font-size.px' key syntax appends the unit directly in the property name — a genuinely useful shorthand when the bound value is a plain number and needs a unit suffix like px, %, or em.

ngStyle with a method returning computed styles

{{ order.status }}
getStatusStyle(status: string): Record {
    const colors: Record = {
        pending: '#f59e0b',
        completed: '#10b981',
        cancelled: '#ef4444',
    };
    return { color: colors[status] ?? '#6b7280', fontWeight: 'bold' };
}

A simpler single-property style binding, without ngStyle at all

Dynamic text

For binding just one or two individual style properties, Angular's direct style binding syntax ([style.property]) is simpler than [ngStyle] with a whole object — ngStyle becomes more worthwhile once several properties need to change together based on the same condition.

ngClass with an object, toggling classes conditionally

Content

Each key in the object is a class name, and its value is a boolean expression — the class is applied only when its corresponding expression evaluates truthy, and multiple classes can be toggled independently in a single binding.

ngClass with an array of class names

Content
sizeClass = 'card-large';
colorClass = 'card-blue';

ngClass with a method for more complex logic

Content
getCardClasses(): Record {
    return {
        'card': true,
        'card-featured': this.product.isFeatured,
        'card-out-of-stock': this.product.stock === 0,
    };
}

A simpler single-class binding, without ngClass

Content

Just like [style.property], Angular supports direct single-class binding ([class.name]) for the common case of toggling exactly one class — reach for [ngClass] once several classes need conditional logic together.

Choosing between the two directives together

A single component often uses both at once — ngClass for structural state (active, disabled, error) that maps to predefined CSS rules, and ngStyle for genuinely computed, data-driven values (a progress bar's width percentage, a color derived from a hex code) that can't reasonably be expressed as a fixed set of classes.