Modifying Appearance with Attribute Directives
In modern web applications, static HTML is rarely enough. We need our interfaces to react to user actions, data changes, and application state. Angular provides **Attribute Directives** to handle this dynamic behavior elegantly. Unlike structural directives (like `*ngIf`) which add or remove elements, attribute directives modify the appearance or behavior of an *existing* element.
The Chameleon: `ngClass`
The `ngClass` directive is your primary tool for handling CSS classes. While standard HTML allows a `class` attribute, `ngClass` unlocks the full power of JavaScript (TypeScript) expressions.
There are three ways to use it:
- String: `[ngClass]="'class1 class2'"`. Simple, but limited.
- Array: `[ngClass]="['class1', 'class2']"`. Good for lists of classes.
- Object (Most Powerful): `[ngClass]="{'active': isActive, 'disabled': !isValid}"`. This allows you to toggle classes based on boolean logic.
✔️ Best Practice
<div [ngClass]="{
'is-active': currentState === 'active',
'is-hidden': isHidden
}">Clean, readable object syntax for conditional classes.
❌ Bad Practice
<div class="{{ isActive ? 'active' : '' }}">Avoid string interpolation for classes; it's messy and harder to maintain.
The Painter: `ngStyle`
While CSS classes are preferred for consistent theming, sometimes you need to set a specific style value dynamically—like a progress bar width, a specific user-selected color, or coordinates for a draggable element.
`ngStyle` accepts an object where keys are CSS properties and values are the style values.
<div [ngStyle]="{ 'width': progress + '%', 'background-color': colorVar }"></div>Pro Tip: Always preferngClassoverngStylewhen possible. Classes are reusable, cacheable by browsers, and keep your templates cleaner. ReservengStylefor truly dynamic values that cannot be predefined in a stylesheet.