Sub topic 4
Conditional styling with class and style bindings
This chapter covers how to switch CSS classes and inline styles on and off from component state. It assumes you can write a standalone Angular component with a signal, you know basic template syntax, and you know how Emulated encapsulation scopes component CSS. The Emulated rule matters here because class bindings only work as expected when the CSS they target is in scope.
Why bindings instead of manual DOM changes
Conditional styling means the look of an element depends on state, such as "this row is selected" or "this bar is 60% full". Angular lets you declare that dependency in the template. When the state changes, Angular updates only the affected class or style. You never call classList.add() or set element.style yourself.
There are two families of binding:
- Class bindings add or remove class names. The CSS rules for those classes live in your stylesheet.
- Style bindings set individual inline CSS properties. The values are computed at run time.
Prefer class bindings when the set of visual states is small and known in advance. Prefer style bindings when the value is continuous or comes from data, such as a width, a position, or a user-chosen color.
Single class bindings
The form [class.name]="condition" adds name when the expression is truthy and removes it when the expression is falsy.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-toggle-row',
template: `
<div class="row" [class.selected]="selected()" [class.is-disabled]="disabled()">
<ng-content />
</div>
<button (click)="selected.set(!selected())">Toggle selection</button>
`,
styles: `
.row { padding: 8px; border: 1px solid #cbd5e1; }
.row.selected { background: #e0e7ff; }
.row.is-disabled { opacity: 0.5; }
`,
})
export class ToggleRowComponent {
selected = signal(false);
disabled = signal(false);
}Three details to remember:
- Hyphenated names such as
is-disabledwork directly afterclass.. - Signals are called like functions in the template (
selected()). Angular tracks the read and updates the class when the signal changes. - A static
class="row"and any number of bindings coexist on the same element. A binding never wipes out the static classes.
Binding several classes at once
When many classes depend on one piece of state, bind [class] to an object, an array, or a string.
| Expression type | Example | Result |
|---|---|---|
| Object | `{ active: a(), 'is-large': b() }` | Keys whose values are truthy are added. |
| Array | `['base', size()]` | Every string in the array is added. |
| String | `'one two'` | Space-separated names are added. |
The object form is usually the clearest. Build it in a computed signal so the template stays short and the logic can be tested.
import { Component, computed, signal } from '@angular/core';
type Status = 'idle' | 'loading' | 'error';
@Component({
selector: 'app-status',
template: `
<p class="status" [class]="statusClasses()" [class.compact]="compact()">
{{ status() }}
</p>
<button (click)="next()">Next status</button>
`,
styles: `
.status { padding: 4px 12px; border-radius: 4px; }
.status.compact { padding: 0 6px; }
.is-idle { background: #e2e8f0; }
.is-loading { background: #fde68a; }
.is-error { background: #fecaca; }
`,
})
export class StatusComponent {
status = signal<Status>('idle');
compact = signal(false);
statusClasses = computed(() => ({
'is-idle': this.status() === 'idle',
'is-loading': this.status() === 'loading',
'is-error': this.status() === 'error',
}));
next() {
const order: Status[] = ['idle', 'loading', 'error'];
const index = order.indexOf(this.status());
this.status.set(order[(index + 1) % order.length]);
}
}The element keeps status from the static attribute. It gets exactly one is-* class from the object and compact from the single binding. Each time you click the button, one is-* class is removed and another is added.
Style bindings
The form [style.property]="value" sets one inline CSS property. Use the CSS property name in kebab-case (background-color). Angular also accepts camelCase (backgroundColor).
A unit suffix after the property name tells Angular to append the unit to a number. These two lines are equivalent:
<div [style.width.px]="width()"></div>
<div [style.width]="width() + 'px'"></div>Common suffixes are .px, .%, .em, and .rem.
Style bindings can also set CSS custom properties, which is a good way to hand a computed value to your stylesheet:
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-meter',
template: `
<div class="track">
<div class="fill"
[style.width.%]="percent()"
[style.--fill-color]="color()"></div>
</div>
<input type="range" min="0" max="100"
[value]="percent()" (input)="onInput($event)" />
`,
styles: `
.track { background: #e5e7eb; border-radius: 4px; }
.fill {
height: 8px;
border-radius: 4px;
background: var(--fill-color, steelblue);
transition: width 150ms;
}
`,
})
export class MeterComponent {
percent = signal(40);
color = computed(() => (this.percent() > 80 ? 'crimson' : 'steelblue'));
onInput(event: Event) {
this.percent.set(Number((event.target as HTMLInputElement).value));
}
}The width is continuous data, so it is bound inline. The color has only two states. It could be a class, but a custom property keeps the decision in TypeScript while the stylesheet still decides how to use the value.
Removing a style
Binding null or undefined removes the inline property. [style.width.px]="null" leaves no width on the element, so the stylesheet value applies again. Binding false is not a removal for style bindings, so use null.
Binding many styles
[style] accepts an object or a string. Keys are CSS property names, and a null value removes that property.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-note',
template: `
<p [style]="noteStyles()">Remember to save your work.</p>
<button (click)="urgent.set(!urgent())">Toggle urgent</button>
`,
})
export class NoteComponent {
urgent = signal(false);
noteStyles = computed(() => ({
color: this.urgent() ? 'crimson' : null,
'font-weight': this.urgent() ? '700' : null,
'border-left': '4px solid #94a3b8',
}));
}How bindings interact with encapsulation
Under Emulated encapsulation, Angular tags every element in a component's template with an attribute such as _ngcontent-abc. It rewrites your selectors to include that attribute. This has three consequences for conditional styling.
- Classes you bind inside the template are scoped.
.selectedin the component'sstylesmatches only elements of this template, even if the class was added at run time. - A class bound on a child component's tag belongs to the parent. In
<app-card [class.featured]="isFeatured()">, the<app-card>element is part of the parent's template. The parent's.featuredrule can match it. The child's styles cannot, unless they use:host(.featured). - Classes added to elements you did not create are not matched. Content from a child's template or from a library does not carry your component's attribute. A rule like
.highlightin your CSS will not reach it, even if you add the class by script.
The third point is the usual cause of "my class is applied, but nothing changes". Check DevTools. If the class is on the element, the problem is scoping, not the binding.
Precedence when several sources set the same thing
An element can receive the same class or style from several places. Angular resolves conflicts in a fixed order, highest priority first:
- Template bindings on the element.
- Host bindings of directives applied to the element.
- Host bindings of the component itself.
- Static values (
class="...",style="...") and stylesheet rules.
Within one source, a specific binding such as [style.width.px] wins over a general one such as [style]. If a higher-priority binding evaluates to undefined, Angular falls through to the next lower source. This lets a component supply a default and a parent override it.
The distinction between null and undefined matters. null removes the property at that level. undefined hands the decision to the next lower source.
ngClass and ngStyle
Angular also ships the NgClass and NgStyle directives. They predate the current binding syntax and behave almost the same way. The native [class] and [style] bindings need no imports, need no extra directive instance, and follow the precedence rules above. Use them in new code. You will still meet ngClass and ngStyle in existing projects, and they work. Do not rewrite working code only for this reason.
Host bindings
The bindings above target elements inside a template. To set classes or styles on the component's own element, use the host metadata with the same syntax, for example '[class.highlighted]': 'highlighted()'. That technique, together with :host selectors, gets its own chapter. Remember that host bindings sit below template bindings in precedence, so a parent can always override them.
Common errors
- Using
[class]="'active'"to toggle. A constant string never changes. Use[class.active]="condition". - Forgetting the unit.
[style.width]="percent()"with a plain number produces an invalid value, so the browser ignores it. Use[style.width.%]. - Binding
falseto remove a style. Usenullinstead. - Reading a signal without calling it.
[class.done]="percent === 100"compares the signal object, not its value. - Rules that lose on specificity. An inline style from a binding beats any normal stylesheet rule. If a stylesheet rule seems ignored, look for a style binding on the same element.
- Overusing style bindings for fixed looks. Colors, spacing, and typography that depend on a few states belong in classes. Inline styles are hard to override from outside and cannot use media queries or pseudo-classes.
Exercise
A parent template contains <app-card [class.featured]="isFeatured()" />. The .featured rule is written in the app-card component's own styles, and the class appears on the element in DevTools, but the card does not change. Under Emulated encapsulation, why does this happen, and what are two ways to fix it?
Show answer
The <app-card> host element belongs to the parent's template, so it carries the parent's scoping attribute, not app-card's. A plain .featured rule in app-card's styles is rewritten to require app-card's attribute and so does not match its own host element. Fix 1: write the rule as :host(.featured) in app-card's styles, which targets the host element. Fix 2: move the .featured rule into the parent's styles, where the element does match. Using a host binding inside app-card with :host(.featured) is a third option that keeps the logic in the component.
Exercise
You have a signal progress holding a number from 0 to 100. Write the template bindings for a div that has a width equal to the progress in percent, gets the class complete only at 100, and sets a custom property --bar-color to 'seagreen' at 100 and 'steelblue' otherwise.
Show answer
<div [style.width.%]="progress()" [class.complete]="progress() === 100" [style.--bar-color]="progress() === 100 ? 'seagreen' : 'steelblue'"></div>. The .% suffix appends the percent unit, [class.complete] toggles on a strict comparison, and the style binding sets the custom property that the stylesheet reads with var(--bar-color).