How to use ViewEncapsulation in Angular
Managing CSS scope in Angular components is critical for preventing style conflicts and maintaining clean component boundaries. With over 12 years of Angular experience since 2014 and as the creator of CoreUI, I’ve used ViewEncapsulation extensively in enterprise applications. Angular provides three ViewEncapsulation modes: Emulated (default), None, and ShadowDom, each controlling how styles are scoped to components. The ViewEncapsulation strategy determines whether component styles affect only that component or leak to the global scope.
Set ViewEncapsulation in the component decorator to control CSS scoping behavior.
import { Component, ViewEncapsulation } from '@angular/core'
@Component({
selector: 'app-card',
template: `
<div class='card'>
<h2>Card Title</h2>
<p>Card content</p>
</div>
`,
styles: [`
.card {
border: 2px solid blue;
padding: 20px;
}
`],
encapsulation: ViewEncapsulation.Emulated
})
export class CardComponent {}
Best Practice Note
ViewEncapsulation.Emulated is the default and recommended mode—it adds unique attributes to elements and scopes styles to the component without using Shadow DOM. ViewEncapsulation.None makes component styles global, useful for overriding third-party library styles. ViewEncapsulation.ShadowDom uses native Shadow DOM for true encapsulation but has limited browser support and CSS framework compatibility. This is the same pattern we use in CoreUI for Angular components to ensure styles remain isolated while allowing theme customization through CSS variables.



