Component styles and encapsulation keep each component's look separate. This stops styles from mixing up and breaking the page design.
0
0
Component styles and encapsulation in Angular
Introduction
When you want each component to have its own unique style without affecting others.
When building a large app with many components to avoid style conflicts.
When you want to easily maintain or update styles for a single component.
When you want to control how styles apply inside or outside a component.
Syntax
Angular
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.css'], encapsulation: ViewEncapsulation.Emulated // or None, ShadowDom }) export class ExampleComponent {}
encapsulation controls how styles apply to the component.
Common options are Emulated (default), None, and ShadowDom.
Examples
Default encapsulation. Styles apply only inside this component using Angular's emulated shadow DOM.
Angular
@Component({
selector: 'app-box',
template: `<div class='box'>Box</div>`,
styles: [`.box { color: blue; }`],
encapsulation: ViewEncapsulation.Emulated
})
export class BoxComponent {}No encapsulation. Styles apply globally to the whole app, affecting all
p tags.Angular
@Component({
selector: 'app-global-style',
template: `<p>Global style</p>`,
styles: [`p { color: red; }`],
encapsulation: ViewEncapsulation.None
})
export class GlobalStyleComponent {}Uses real Shadow DOM. Styles are fully isolated inside the component's shadow root.
Angular
@Component({
selector: 'app-shadow',
template: `<button>Shadow DOM</button>`,
styles: [`button { background: yellow; }`],
encapsulation: ViewEncapsulation.ShadowDom
})
export class ShadowComponent {}Sample Program
This component styles the paragraph text green and bold. Because of Emulated encapsulation, these styles only affect this component's paragraph, not others on the page.
Angular
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-style-demo', template: ` <h2>Encapsulation Demo</h2> <p class="text">This text is styled inside the component.</p> `, styles: [ `.text { color: green; font-weight: bold; }` ], encapsulation: ViewEncapsulation.Emulated }) export class StyleDemoComponent {}
OutputSuccess
Important Notes
Emulated is the default and works well for most cases.
Use None if you want styles to affect the whole app, but be careful to avoid conflicts.
ShadowDom requires browser support but gives the strongest style isolation.
Summary
Component styles keep each part of your app looking right without mixing styles.
Encapsulation controls how styles apply: Emulated, None, or ShadowDom.
Choose the right encapsulation to balance style isolation and app needs.