Angular Components Created: 06 Jan 2026 Updated: 06 Jan 2026

Class/Style Binding

Step 1: Class Binding (The Boolean Toggle)

Class binding is used to add or remove CSS classes based on a condition. This is the preferred method because it keeps your CSS logic inside your stylesheet.

A. Toggling a Single Class

The syntax is [class.name-of-class]="condition"


<div [class.active-server]="server.isActive">
{{ server.name }}
</div>

B. Managing Multiple Classes (Object Syntax)

When a component has multiple states (e.g., Selected, Warning, Disabled), you can pass an object where the keys are class names and the values are booleans.


serverState = {
'is-online': true,
'has-error': false,
'high-load': true
};


<div [class]="serverState">Server Status</div>

Step 2: Style Binding (Granular Control)

Style binding is used for values that are calculated at runtime and cannot be predefined in a CSS file, such as a progress bar width or a dynamic color picker.

A. Single Property with Units

Angular allows you to specify the unit (px, %, em) directly in the binding.


<div [style.width.%]="cpuUsage"></div>

<p [style.color]="isCritical ? 'red' : 'green'">System Health</p>

B. Multi-Style Objects

Just like classes, you can use an object to apply several inline styles simultaneously.


customStyles = {
'font-weight': 'bold',
'border-left': '5px solid #333',
'opacity': 0.8
};


<section [style]="customStyles">Configuration Panel</section>

Step 3: Real-World Implementation (Microservice Monitor)

Let's combine everything into a "Service Health" card. We will use Event Binding to update the state, which in turn updates the Class and Style bindings.

component.ts


export interface Service {
id: number;
name: string;
status: 'running' | 'stopped';
load: number; // 0-100
}

@Component({ ... })
export class MonitorComponent {
service: Service = { id: 1, name: 'Order-API', status: 'running', load: 75 };

toggleService() {
this.service.status = this.service.status === 'running' ? 'stopped' : 'running';
this.service.load = this.service.status === 'running' ? 40 : 0;
}
}

component.html


<div class="card"
[class.border-success]="service.status === 'running'"
[class.border-danger]="service.status === 'stopped'">
<h3>{{ service.name }}</h3>

<div class="progress-bg">
<div class="bar"
[style.width.%]="service.load"
[style.background-color]="service.load > 80 ? 'red' : 'blue'">
</div>
</div>

<button (click)="toggleService()">
{{ service.status === 'running' ? 'Stop' : 'Start' }} Service
</button>
</div>
Binding TypeSyntaxBest Use Case
Single Class[class.name]="bool"Simple states (Active, Hidden, Selected).
Multi Class[class]="object"Complex UI states with overlapping rules.
Single Style[style.prop]="val"Calculated values (Width, Height, Color).
Multi Style[style]="object"Grouped visual transformations.


Share this lesson: