Angular Shadow DOM and View Encapsulation

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:02:00

ViewEncapsulation in Angular

ViewEncapsulation is an Angular feature that controls how styles are applied to components. It has three modes: Emulated, None, and ShadowDom. Emulated encapsulation (the default) scopes styles to the component, None removes encapsulation, and ShadowDom uses the browser's native shadow DOM to isolate styles.

Example

// Example of using ViewEncapsulation in a component
@Component({
  selector: 'app-example',
  template: '<p class="red-text">This text is styled.</p>',
  styles: ['.red-text { color: red; }'],
  encapsulation: ViewEncapsulation.Emulated
})
export class ExampleComponent {}

Emulated ViewEncapsulation

Emulated ViewEncapsulation (the default) emulates shadow DOM behavior by scoping component styles to the component's host element. It adds unique attributes to the component's elements to prevent style leakage.

Example

// Example of using Emulated ViewEncapsulation
@Component({
  selector: 'app-emulated',
  template: '<p class="blue-text">This text is styled.</p>',
  styles: ['.blue-text { color: blue; }'],
  encapsulation: ViewEncapsulation.Emulated
})
export class EmulatedComponent {}

None ViewEncapsulation

None ViewEncapsulation removes style encapsulation entirely. This means that styles defined in a component can affect elements outside the component. Use with caution as it can lead to style conflicts in larger applications.

Example

// Example of using None ViewEncapsulation
@Component({
  selector: 'app-none',
  template: '<p class="green-text">This text is styled.</p>',
  styles: ['.green-text { color: green; }'],
  encapsulation: ViewEncapsulation.None
})
export class NoneComponent {}

ShadowDom ViewEncapsulation

ShadowDom ViewEncapsulation utilizes the browser's native shadow DOM to isolate component styles. It's the most encapsulated mode, ensuring that component styles do not leak to the global scope.

Example

// Example of using ShadowDom ViewEncapsulation
@Component({
  selector: 'app-shadow-dom',
  template: '<p class="purple-text">This text is styled.</p>',
  styles: ['.purple-text { color: purple; }'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class ShadowDomComponent {}
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this