Sub topic 13
Choosing a styling strategy for your application
This chapter assumes you have read the earlier chapters on component styles, Emulated encapsulation, :host, class and style bindings, the three ViewEncapsulation modes, global styles, CSS custom properties, host bindings and ::ng-deep. It does not introduce new APIs. It gives you a way to decide which of those tools to use for a given problem, and what goes wrong when you pick badly.
Start from the default and justify every departure
Angular's default, Emulated encapsulation, fits most components. At build time Angular adds a generated attribute, such as _ngcontent-abc-c12, to each element in a component's template. It rewrites each selector in the component's styles to require that attribute. The result is that a .label rule in one component cannot match a .label element in another.
Treat Emulated as the baseline. Move away from it only when you can name the requirement that forces you to. Three requirements justify a departure:
- A hard isolation boundary is needed, which points to
ShadowDom. - Styles must be shared across the whole document, which points to global stylesheets (or, rarely,
None). - You must style markup you do not own, such as a third-party widget or HTML inserted at runtime.
The tools, compared
| Tool | Scope | Reaches into children? | Main risk |
|---|---|---|---|
| Component `styles` / `styleUrl` (Emulated) | This component's template | No | None significant. Selectors cannot target child component internals. |
| `:host`, `:host(.x)`, `:host-context(...)` | The component's own host element | Not applicable | `:host-context` depends on ancestor markup, which couples the component to its usage. |
| Class and style bindings | One element in a template | No | Logic spreads into the template if conditions grow complex. |
| Host bindings (`host` metadata) | The host element | No | Hidden from the parent's template, so reviewers may miss them. |
| Global stylesheet | Whole document | Yes, to anything not in a Shadow DOM | Specificity fights and accidental matches. |
| CSS custom properties | Inherited down the tree | Yes, through inheritance, including Shadow DOM | Naming collisions and missing fallbacks. |
| `ViewEncapsulation.None` | Whole document, once the component is created | Yes | Leaks in both directions. |
| `ViewEncapsulation.ShadowDom` | Native shadow root | Only inherited properties and custom properties cross | Global styles do not apply inside. |
| `::ng-deep` | Rule is no longer scoped past that point | Yes | Deprecated. Can leak. |
The rest of this chapter turns the table into a decision procedure.
A decision procedure
Work through these questions in order and stop at the first one that applies.
Step 1: Your own component, no outside influence
Write the styles in the component and leave encapsulation alone. This is the case from the first chapter:
import { Component } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label"><ng-content /></span>`,
styles: `
:host {
display: inline-block;
}
.label {
padding: 2px 8px;
border-radius: 4px;
background: #e0e7ff;
}
`,
})
export class BadgeComponent {}Use styleUrl instead of styles when the stylesheet grows beyond a screenful, or when you want Sass. Both produce the same encapsulation behavior, so the choice is about readability, not scoping.
Step 2: State that changes at runtime
Choose the narrowest binding that does the job.
- Use
[class.done]="..."or[style.width.%]="..."for one element inside the template. - Use a host binding for a class or style on the component's own element. This keeps the parent from needing to know your internals.
- Prefer a class binding over a style binding when the value is one of a few states. Class names keep the actual CSS in the stylesheet, where it can be reviewed and overridden. Use a style binding when the value is continuous, like a percentage.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-progress',
template: `
<div class="bar"
[class.done]="percent() === 100"
[style.width.%]="percent()"></div>
`,
styles: `
.bar { height: 8px; background: steelblue; }
.bar.done { background: seagreen; }
`,
})
export class ProgressComponent {
percent = signal(40);
}Step 3: Values that a parent or theme must control
Expose custom properties and give each one a fallback. The component stays encapsulated, and the outside world controls only the values you chose to publish.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-card',
template: `<ng-content />`,
styles: `
:host {
display: block;
padding: var(--card-padding, 16px);
background: var(--card-background, white);
}
:host(.highlighted) {
outline: 2px solid orange;
}
`,
host: {
'[class.highlighted]': 'highlighted()',
},
})
export class CardComponent {
highlighted = input(false);
}The global stylesheet can then theme every card without piercing anything:
/* styles.css (global) */
app-card {
--card-background: #f8fafc;
--card-padding: 24px;
}For application-wide design tokens, declare them once on :root, and map them to component-level properties only where a component needs its own override point:
:root {
--color-surface: #ffffff;
--color-accent: #4f46e5;
--space-3: 16px;
}A component can then write background: var(--card-background, var(--color-surface));. The fallback chain gives you a component-specific hook and an application-wide default.
Step 4: Third-party or runtime markup
Angular's encapsulation attribute is only added to elements Angular's template compiler produced. HTML from innerHTML, a charting library, or a rich text editor has no such attribute, so a component style never matches it. Try these options in order:
- Custom properties or documented theming hooks. If the library exposes them, use them.
- Global styles under a wrapper class. Put a class such as
vendor-charton a container in your template, and write.vendor-chart .chart-title { ... }instyles.css. The wrapper class keeps the rule from matching unrelated elements. :host ::ng-deep. Use this only when options 1 and 2 are not possible.
:host ::ng-deep .third-party-title {
font-weight: 700;
}Prefixing with :host keeps the rule limited to descendants of this component. A bare ::ng-deep .third-party-title becomes a global rule, which is the leak you were trying to avoid.
Choosing an encapsulation mode
Once a component needs more than the default, pick the mode by the problem it solves.
ShadowDomfits a component that must look the same wherever it is embedded, such as a widget dropped into pages you do not control. Global styles stop at the shadow root, so any global resets or typography you rely on will not apply inside, and you must import or restate them. Inherited properties (color,font-family) and custom properties still cross the boundary, which is why custom properties remain the theming channel here.Nonefits a component whose job is to emit global styles, for example a layout shell or a component that styles markup from a rendering library. Its CSS applies to the whole document once the component has been created, and global CSS also reaches into it. Any rule you write must be written as if it were instyles.css, with a naming convention to avoid collisions.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-widget',
template: `<p class="note">Isolated by a shadow root</p>`,
styles: `.note { color: darkgreen; }`,
encapsulation: ViewEncapsulation.ShadowDom,
})
export class WidgetComponent {}Common failure modes
- A style does nothing. Check whether the target element belongs to a child component or was inserted at runtime. Emulated styles do not reach either. Inspect the element in DevTools: if it lacks the
_ngcontent-*attribute that your rule's selector requires, that is the cause. - A style appears in the wrong place. Look for a
None-mode component or a bare::ng-deepin the codebase. Both produce unscoped rules. - Global styles are ignored in a
ShadowDomcomponent. This is expected. Move the shared rules into the component, or expose them as custom properties. - A custom property has no effect. Confirm it is set on the element itself or an ancestor, not on a descendant. Custom properties inherit downward only. Also check for typos, because a misspelled name silently falls back to the default.
- Specificity fights. Emulated encapsulation adds an attribute selector, which raises the specificity of component rules. A global rule can lose to a component rule even when it appears later. Fix this by lowering your own specificity or by publishing a custom property, not by adding
!important.
A practical default for an application
- Put design tokens (colors, spacing, type scale) as custom properties on
:root, along with resets and base typography, in the global stylesheet. - Style each component with Emulated encapsulation and consume tokens through
var()with fallbacks. - Expose a small, named set of component-level custom properties for anything a parent should adjust.
- Use host bindings and
:host(...)for state on the component's own element. - Reserve
ShadowDomfor components that need real isolation,Nonefor the rare style-emitting component, and::ng-deepfor documented third-party exceptions.
Exercise
A team uses a charting library that renders SVG text into a div inside your ChartPanelComponent. The library gives no theming hooks. Your component style .axis-label { fill: gray; } has no effect. Name two ways to fix it, and say which you would try first and why.
Show answer
First, add a wrapper class (for example chart-panel) on the container in the template and write .chart-panel .axis-label { fill: gray; } in the global stylesheet. This works because global rules are not tied to the _ngcontent attribute that the library's elements lack, and the wrapper class keeps the rule from matching unrelated elements. Second, write :host ::ng-deep .axis-label { fill: gray; } in the component. Try the global wrapper-class rule first, because ::ng-deep is deprecated. If you do use ::ng-deep, keep the :host prefix so the rule does not leak.
Exercise
A ShadowDom component sets background: var(--panel-bg, white). The application's global stylesheet contains .panel { background: lightblue; } and the component's inner element has class panel. The background stays white. Explain why, and how to make it lightblue.
Show answer
Global selectors do not match elements inside a shadow root, so the .panel rule never applies. Custom properties do inherit across the boundary, so set --panel-bg: lightblue; on the component's host element or an ancestor, for example app-panel { --panel-bg: lightblue; } in the global stylesheet.