Sub topic 2
Choosing a ViewEncapsulation Mode
Assume you know basic CSS selectors, specificity, Angular templates, and standalone components. Angular uses view encapsulation to control which styles can affect a component's template.
Choosing a ViewEncapsulation mode
Angular provides three modes:
| Mode | How styles are scoped | Best use |
|---|---|---|
| `Emulated` | Angular adds attributes to selectors and elements | Default choice for most components |
| `ShadowDom` | The browser creates a native shadow root | Strong browser-level isolation |
| `None` | Styles become global | Deliberate global or legacy styles |
Emulated is the default. Angular transforms a rule such as .label so that it matches only elements in that component's view. This gives local behavior without requiring native Shadow DOM.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-widget',
template: `<p class="note">Private component styling</p>`,
styles: `.note { color: darkgreen; }`,
encapsulation: ViewEncapsulation.Emulated,
})
export class WidgetComponent {}Choose ShadowDom when browser-native isolation matters. Global styles cannot reach into the shadow root, and the component's styles cannot escape it. This can make integration harder when an application needs to control the component from outside.
Choose None only when the rules are intentionally global. A selector such as .note can then affect unrelated elements throughout the application.
The boundary can be pictured like this:
Global styles and where they belong
Put application-wide rules in a global stylesheet, such as src/styles.css. Typical examples include a CSS reset, typography defaults, layout utilities, and styles for third-party libraries.
Keep component-specific rules in the component's styles or styleUrl metadata. Global selectors should not be the default way to style component internals because they create hidden dependencies and specificity conflicts.
Theming across component boundaries with CSS custom properties
CSS custom properties, also called CSS variables, cross an Emulated boundary safely. Define them on the component element or an ancestor, then read them inside the component.
/* src/styles.css */
app-card {
--card-background: #f8fafc;
--card-padding: 24px;
}@Component({
selector: 'app-card',
template: `<ng-content />`,
styles: `
:host {
display: block;
padding: var(--card-padding, 16px);
background: var(--card-background, white);
}
`,
})
export class CardComponent {}The fallback after the comma applies when the custom property is undefined. This approach preserves encapsulation while allowing documented theme values to cross the component boundary.
Exercise
Which mode should you choose for an ordinary Angular component, and how can a parent theme it?
Show answer
Choose Emulated encapsulation. Expose CSS custom properties and set them on the component element or an ancestor.