Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 74 ยท Components in Depth

Styling Components and View Encapsulation

Understand Angular component styles, styleUrl, Emulated, ShadowDom and None encapsulation, :host, ::ng-deep and CSS variable theming with live demos.

In plain HTML and CSS, every style rule is global: a rule for p hits every paragraph on the page, and large projects spend years fighting that. Angular components solve it by attaching styles to a component and making them apply only to that component's template. You can write simple selectors like h2 or .title inside a component without worrying that they will leak out or that someone else's styles will leak in.

How that isolation works is called view encapsulation. Angular offers three modes, and understanding them explains almost every "why isn't my style applied?" question. This lesson covers where component styles live, how the default mode really works, the :host selector, why ::ng-deep is a last resort, and how to theme components with CSS custom properties.

Real Angular vs stand-in. The typescript and css blocks that use @Component are real Angular and read-only on this site. The runnable demos re-create the mechanism in plain TypeScript and in the browser (attributes plus rewritten selectors, and native Shadow DOM) so you can see what each mode does. They are not Angular's compiler. If you are new to CSS selectors, start with the CSS tutorial.

Where component styles live

A component can declare styles inline, or point at a file:

TypeScript
import { Component } from '@angular/core';

@Component({
  selector: 'app-badge',
  template: `<span class="badge"><ng-content /></span>`,
  styles: `
    .badge {
      padding: 0.15rem 0.6rem;
      border-radius: 999px;
      background: #e6f0ff;
      color: #1a3d7c;
    }
  `,
})
export class BadgeComponent {}

For longer styles, use a separate file with styleUrl (a single file; the plural styleUrls array is the older form, still supported):

TypeScript
@Component({
  selector: 'app-badge',
  templateUrl: './badge.component.html',
  styleUrl: './badge.component.css',
})
export class BadgeComponent {}

Global styles live elsewhere: files listed in the styles array of the build target in angular.json (usually src/styles.css). Put resets, fonts, design tokens and layout helpers there. Put everything specific to one component in the component's own styles.

Emulated: the default

The default mode, ViewEncapsulation.Emulated, fakes isolation with attributes. During compilation, Angular does two things:

  1. It adds a generated attribute to every element in the component's template, something like _ngcontent-ng-c3482651 (the number differs per component).
  2. It rewrites each selector in the component's styles to require that attribute, so h2 { color: teal } becomes h2[_ngcontent-ng-c3482651] { color: teal }.

The host element (the component's own tag) gets a matching _nghost-... attribute, which is what :host selects. A style written in one component therefore cannot match elements that belong to another component's template, because those elements carry a different attribute. The cost is small: no JavaScript at runtime, just a few attributes and slightly longer selectors.

flowchart LR
  S["Component CSS<br/>h2 { color: teal }"] --> R["Angular compiler"]
  R --> O["h2[_ngcontent-c1] { color: teal }"]
  T["Template<br/>h2 element"] --> R
  R --> E["h2 with attribute _ngcontent-c1"]
  O -.->|"matches only"| E

The compiler rewrites the selector and stamps the same attribute on the template's elements, so the two meet only inside this component.

The next stand-in is a simplified version of that selector rewriting, written in TypeScript. It is much smaller than Angular's real processor (it only handles simple selectors), but it produces output in the same style.

TypeScript Stand-in: rewriting selectors for Emulated mode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the last two rules. :host(.active) .title becomes [_nghost-ng-c1].active .title[_ngcontent-ng-c1], so it only applies when the host has the class active. In the ::ng-deep rule, the p is left without an attribute, which is why it can reach into other components' elements.

The :host selector

Because a component's template cannot style its own tag, :host is how a component styles itself:

CSS
:host {
  display: block;
  margin-block: 1rem;
}

:host(.compact) {
  margin-block: 0.25rem;
}

:host(:hover) .title {
  text-decoration: underline;
}

Custom elements are display: inline by default, which is almost never what you want for a component that holds blocks, so :host { display: block; } is a common first rule. :host(.compact) matches when the host has that class, :host-context(.dark) matches when an ancestor has it, and a parent can also style a child's tag from the parent's own stylesheet. That works because the child's host element is part of the parent's template and so carries the parent's attribute:

CSS
/* in the parent's styles */
app-badge {
  margin-left: 0.5rem;
}

What the parent cannot do is reach into the child's template (the span inside app-badge), because those elements carry the child's attribute.

ShadowDom and None

The other two modes live on the component's encapsulation property:

TypeScript
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-widget',
  template: `<p>Isolated for real</p>`,
  styles: `p { color: crimson; }`,
  encapsulation: ViewEncapsulation.ShadowDom,
})
export class WidgetComponent {}
Mode How it isolates Global styles reach inside? Component styles leak out?
Emulated (default) attributes + rewritten selectors yes, global CSS still applies no
ShadowDom the browser's native shadow DOM no (only inherited properties and CSS variables get in) no
None nothing: styles become global yes yes

ShadowDom gives the strongest isolation, which suits widgets that are embedded in unknown pages, but it also means your global design system, utility classes and resets do not apply inside, so it is less common in ordinary apps. None is useful when you deliberately want a component to ship global rules, for example a component that styles markup coming from a rich-text editor.

Try Emulated and None side by side. Components A and B both define p { ... } with different colors, and each only affects its own paragraph. Component C starts as Emulated too; press the button to switch it to None and watch its p rule leak into A and B.

Stand-in: Emulated scoping and the None leak

The text under the button shows the CSS that the page uses. In Emulated mode, each rule ends with the component's attribute; in None mode, C's rule is plain p { ... }, so it matches every paragraph in the page.

::ng-deep and why to avoid it

The ::ng-deep pseudo-class turns off scoping for everything that follows it, so a parent can style the insides of a child:

CSS
:host ::ng-deep .some-child-class {
  color: crimson;
}

Angular's documentation marks ::ng-deep as deprecated, and it is easy to misuse. Without the leading :host the rule becomes global and bleeds into the whole application. Even with :host it couples the parent to the child's internal markup, which can change at any time. Reach for it only when you have to restyle a third-party component that gives you no other hook, and always prefix it with :host.

Theming with CSS custom properties

CSS custom properties (variables) inherit and are not blocked by Emulated encapsulation or by Shadow DOM. That makes them the right interface between a component and its users. The component reads variables with fallbacks; the application sets them wherever it likes:

CSS
/* in the component */
:host {
  background: var(--card-bg, white);
  color: var(--card-fg, #222);
  border-radius: var(--card-radius, 8px);
}
CSS
/* global styles.css */
:root {
  --card-bg: #fafafa;
}

.dark {
  --card-bg: #1c1c24;
  --card-fg: #eee;
}

You can also set a variable from a template with a style binding such as [style.--card-bg]="color()". See Custom Properties for the CSS side and Design Tokens and Theming for building a whole theme.

This demo uses real Shadow DOM. The page has a global p { color: crimson; } rule, but the paragraph inside the shadow root ignores it. The --accent variable passes through the boundary, so changing it recolors the heading.

Stand-in: Shadow DOM blocks global rules, not variables

A note on Tailwind and utility classes

Utility-first CSS frameworks such as Tailwind work with Angular because their classes are global classes that you write into templates. Emulated encapsulation does not interfere with global classes, so class="flex gap-2 p-4" works in any component. Follow the framework's current Angular setup guide to wire it into the build. One thing to know: using Tailwind directives such as @apply inside a component stylesheet needs extra setup, because each component stylesheet is processed separately. For most teams, the simplest route is utility classes in templates plus design tokens as CSS variables.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the default Emulated mode, how does Angular keep a component's p { color: red; } from affecting other components?

    Emulated mode stamps generated attributes on the template's elements and appends the same attribute to every selector in the component's CSS.
  2. 2. What does :host { display: block; } style?

    :host selects the element that the component's selector matched. Custom elements are inline by default, so display: block is common.
  3. 3. Which encapsulation mode makes component styles global?

    ViewEncapsulation.None skips all isolation, so the styles apply to the whole page.
  4. 4. Why are CSS custom properties good for theming components?

    Variables set on an ancestor are inherited by the component's elements, so the app can set them and the component can read them, with fallbacks.
  5. 5. A parent wants to add a margin to <app-badge> itself (not to what is inside it). What works?

    The child's host element belongs to the parent's template, so the parent's scoped rules can style it. Only the child's internals are out of reach.

Summary

  • Put component-specific CSS in styles or styleUrl; keep resets, fonts and tokens in the global styles.css.
  • Emulated (default) stamps generated attributes on elements and rewrites selectors; ShadowDom uses the browser's shadow root; None makes the styles global.
  • :host, :host(.x) and :host-context(.x) style the component's own tag; a parent can style a child's tag, but not the child's internals.
  • ::ng-deep is deprecated and global without a :host prefix; use it only as a last resort.
  • CSS custom properties cross the boundary and are the best way to theme components.

Next: Attribute and Structural Directives