Sub topic 14
Styling Components and View Encapsulation
This chapter assumes you know CSS selectors and specificity. It also assumes you have built standalone components with a selector, a template, and a class, and that you have used content projection with ng-content. You will learn where component styles live, how Angular keeps them from leaking into other components, and how to work with that scoping when you need to style the host element, projected content, or a child component.
Where Component Styles Live
Each component can carry its own CSS. Angular gives you two ways to attach it:
| Metadata property | Value | Use when |
|---|---|---|
| `styles` | An inline CSS string (or an array of strings) | Styles are short and belong next to the template |
| `styleUrl` | A path to one stylesheet | Styles are long, or you want CSS tooling on a separate file |
| `styleUrls` | An array of paths | You split styles across several files (older form, still supported) |
import { Component } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span class="label">New</span>`,
styles: `
.label {
background: #0b5;
color: white;
padding: 0.125rem 0.5rem;
border-radius: 999px;
}
`
})
export class BadgeComponent {}The .label rule here applies only to elements in BadgeComponent's own template. If another component also uses class="label", this rule does not reach it. That scoping is called view encapsulation.
Styles that should apply to the whole application, such as resets, fonts, and typography, go in the global stylesheet (src/styles.css by default, listed under styles in angular.json). Global styles are not encapsulated.
How Emulated Encapsulation Works
The default mode is ViewEncapsulation.Emulated. Angular imitates Shadow DOM scoping with generated attributes:
- The compiler gives each component type a unique ID, such as
ng-c1234. - The host element (
<app-badge>) gets an_nghost-ng-c1234attribute. - Every element in that component's template gets an
_ngcontent-ng-c1234attribute. - Every selector in the component's CSS is rewritten to require that attribute.
At runtime the DOM looks roughly like this:
<app-badge _nghost-ng-c1234>
<span _ngcontent-ng-c1234 class="label">New</span>
</app-badge>The CSS that ends up in the document head looks like this:
.label[_ngcontent-ng-c1234] {
background: #0b5;
color: white;
padding: 0.125rem 0.5rem;
border-radius: 999px;
}Encapsulation works in one direction only. Component styles cannot leak out, but global styles still leak in. A global span { color: red; } rule reaches the badge's <span>, and the rewritten rule then wins only if its specificity is higher or equal and it comes later. The added attribute selector raises specificity by one attribute, which usually beats a plain element selector from global CSS.
Styling the Host Element with :host
The host element (<app-badge>) belongs to the parent's template, so ordinary selectors in the component's own CSS cannot reach it. Use :host, which Angular rewrites to [_nghost-ng-c1234].
Custom elements are display: inline by default. Forgetting this often causes layout bugs, because width, margin, and padding behave differently than you expect.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-panel',
template: `<ng-content />`,
host: { '[class.active]': 'active()' },
styles: `
:host {
display: block;
padding: 1rem;
border: 1px solid #ccc;
}
:host(.active) {
border-color: #0b5;
}
:host-context(.dark-theme) {
background: #222;
color: #eee;
}
`
})
export class PanelComponent {
active = input(false);
}:host(.active)matches the host only when the host itself has theactiveclass. The parentheses are required.:host.activeis not valid here.:host-context(.dark-theme)matches when the host or any of its ancestors hasdark-theme, for example on<body>.
The host metadata line adds the active class to the host element. Host bindings get their own chapter later. Here, it only shows where the class comes from.
Projected Content and Child Components
Two cases surprise most developers.
Projected content is styled by the parent. In <app-panel><p>Hi</p></app-panel>, the <p> is declared in the parent's template, so it carries the parent's _ngcontent attribute. PanelComponent's rule p { margin: 0; } will not match it.
A child's internals are off-limits. A parent's .label rule does not reach the <span class="label"> inside <app-badge>. The parent can style the <app-badge> host element itself, because that element sits in the parent's template.
The cleanest way to let outside code customize a component is CSS custom properties. Custom properties inherit through the DOM, and encapsulation does not block inheritance.
import { Component } from '@angular/core';
import { BadgeComponent } from './badge.component';
@Component({
selector: 'app-themed-badge',
template: `<span class="label"><ng-content /></span>`,
styles: `
.label {
background: var(--badge-bg, #0b5);
color: var(--badge-fg, white);
padding: 0.125rem 0.5rem;
border-radius: 999px;
}
`
})
export class ThemedBadgeComponent {}
@Component({
selector: 'app-header',
imports: [ThemedBadgeComponent, BadgeComponent],
template: `
<app-themed-badge class="warning">Beta</app-themed-badge>
<app-badge />
`,
styles: `
.warning {
--badge-bg: #e90;
--badge-fg: black;
}
`
})
export class HeaderComponent {}The parent sets variables on the host element, which it is allowed to style. The child reads them, with a fallback after the comma.
Choosing an Encapsulation Mode
You set the mode per component with the encapsulation property:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-shadow-box',
template: `<p>Inside a real shadow root</p>`,
styles: `p { color: rebeccapurple; }`,
encapsulation: ViewEncapsulation.ShadowDom
})
export class ShadowBoxComponent {}| Mode | How scoping works | Global styles reach inside? | Typical use |
|---|---|---|---|
| `Emulated` (default) | Generated attributes and rewritten selectors | Yes | Almost all components |
| `ShadowDom` | Native shadow root on the host | No, except inherited properties and custom properties | Embeddable widgets, web components |
| `None` | No rewriting. Styles become global when the component first renders | Yes, and the component's styles leak out too | Theming a third-party library on purpose |
With ShadowDom, your global typography and utility classes stop working inside the component. Third-party libraries that expect to find elements with document.querySelector may also break. Choose it only when you actually need isolation in both directions.
Common Errors
- Host collapses or ignores width: add
:host { display: block; }. - Rule doesn't affect projected content: move the rule to the parent component, or style a wrapper element in the child's own template.
- Parent can't restyle a child: expose CSS custom properties instead of using
::ng-deep. - Unexpected global override: a global stylesheet rule with higher specificity, or
!important, is beating the component rule. Inspect the element in DevTools and compare the selectors.
Exercise
A CardComponent's CSS contains h2 { color: navy; }. A parent uses <app-card><h2 card-title>Profile</h2></app-card>, and the heading is not navy. Explain why, and give two fixes that avoid ::ng-deep.
Show answer
The <h2> is declared in the parent's template, so it carries the parent's ngcontent attribute, while CardComponent's rule was rewritten to h2[ngcontent-<card id>]. The rule cannot match. Fix 1: move the rule into the parent's styles. Fix 2: style the wrapper the card owns, for example header { color: navy; }, and let color inherit into the projected h2. A variant of fix 2 is to set color: var(--card-title-color, navy) on the header so callers can override it.
Exercise
You set :host.active { border-color: green; } and it never applies, even though the host has the active class. What is wrong?
Show answer
The selector form is wrong. Angular expects the functional form :host(.active), which it rewrites to [_nghost-xxx].active. Write :host(.active) { border-color: green; }.
Exercise
A component uses ViewEncapsulation.ShadowDom, and a global .btn utility class from styles.css no longer styles a button inside it. Why, and what is one way to keep using shared design tokens?
Show answer
A shadow root blocks outside selectors from matching elements inside it, so global class rules do not apply. Inherited properties and CSS custom properties still pass through. Define the tokens as custom properties on :root, for example --btn-bg, and read them with var() in the component's own styles. You can also switch back to Emulated if you don't need isolation in both directions.