Performance: Component styles and encapsulation
This affects how quickly styles apply to components and how much the browser repaints or reflows when styles change.
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-good-style', template: `<div class='box'>Hello</div>`, styles: [`.box { color: red; }`], encapsulation: ViewEncapsulation.Emulated }) export class GoodStyleComponent {}
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-bad-style', template: `<div class='box'>Hello</div>`, styles: [`.box { color: red; }`], encapsulation: ViewEncapsulation.None }) export class BadStyleComponent {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Global styles (ViewEncapsulation.None) | No extra DOM nodes | Multiple reflows if styles affect many elements | High paint cost due to wide style impact | [X] Bad |
| Scoped styles (ViewEncapsulation.Emulated) | Adds attribute selectors to DOM nodes | Single reflow limited to component | Lower paint cost due to scoped styles | [OK] Good |
ViewEncapsulation.Emulated do in Angular component styles?@Component({
selector: 'app-box',
template: `Hello`,
styles: [`.box { color: red; }`],
encapsulation: ViewEncapsulation.None
})
export class BoxComponent {}box in the entire app?box elements in the app will be red. -> Option A@Component({
selector: 'app-test',
template: `Test
`,
styles: [`p { font-weight: bold; }`],
encapsulation: ViewEncapsulation.ShadowDom
})
export class TestComponent {}p text is not bold in the browser. What is the likely cause?Pass the test and this pattern moves unknown