Attribute Directives (ngClass, ngStyle)
Dynamically bind CSS classes and inline styles using Angular's built-in attribute directives.
What Is an Attribute Directive?
Unlike a structural directive, an attribute directive changes the appearance or behavior of an existing element without adding or removing it from the DOM — ngClass and ngStyle are the two most commonly used built-in ones.
ngClass
ngClass accepts an object whose keys are class names and whose values determine whether each class is applied.
@Component({ selector: 'app-status', standalone: true, imports: [CommonModule], template: ` <div [ngClass]="{ active: isActive, error: hasError }"> Status indicator </div> `,})export class StatusComponent { isActive = true; hasError = false;}Direct Class Binding
For a single conditional class, Angular's own class binding syntax is more concise than ngClass and needs no extra import.
<div [class.active]="isActive">Status indicator</div>ngStyle
ngStyle accepts an object of camelCase CSS properties, similarly to ngClass.
@Component({ selector: 'app-text', standalone: true, imports: [CommonModule], template: ` <p [ngStyle]="{ color: textColor, fontSize: fontSize + 'px' }"> Styled text </p> `,})export class TextComponent { textColor = 'red'; fontSize = 16;}For a single style property, direct style binding avoids the ngStyle import entirely.
<p [style.color]="textColor">Styled text</p>Where possible, toggle a CSS class instead of computing raw style objects — it keeps styling in your stylesheet and usually performs better for anything beyond a one-off dynamic value.
FAQs
Yes — both come from CommonModule, which a standalone component must add to its imports array.
Yes — Angular merges a static class="..." attribute with whatever ngClass or [class.x] bindings add or remove.
Summary
ngClass/ngStyle (or their more concise single-property equivalents) give you full control over dynamic styling. Next, you'll learn pipes, for transforming displayed values directly in a template.