Performance: Inline vs external styles
This affects page load speed and rendering performance by influencing CSS parsing, caching, and style recalculations.
import { Component } from '@angular/core'; @Component({ selector: 'app-good-style', template: `<div class="text-red">Hello</div>`, styleUrls: ['./good-style.component.css'] }) export class GoodStyleComponent {} /* good-style.component.css */ .text-red { color: red; font-size: 2rem; }
import { Component } from '@angular/core'; @Component({ selector: 'app-bad-style', template: `<div style="color: red; font-size: 2rem;">Hello</div>` }) export class BadStyleComponent {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline styles | No extra DOM nodes, but increases HTML size | Triggers style recalculation per element | Higher paint cost due to blocking | [X] Bad |
| External stylesheets | No extra DOM nodes, smaller HTML | Single style recalculation after CSS load | Lower paint cost, non-blocking | [OK] Good |
styles property is used to define inline CSS styles directly inside the component decorator.styles and styleUrlsstyleUrls is used for external CSS files, not inline styles.styles array in the component decorator -> Option Cstyles property [OK]styles, external in styleUrls [OK]styles with styleUrlstemplatestyleUrls (plural, camelCase) to link external CSS files.styleUrls array [OK]styleUrls with array of CSS files for external styles [OK]styleUrl instead of styleUrlsstyles instead of styleUrlsstyleSheetsstyles and styleUrls in an Angular component decorator?styles (inline) and styleUrls (external) when both are present.@Component({
selector: 'app-test',
styles: 'h1 { color: red; }',
styleUrls: ['test.component.css']
})styles propertystyles must be an array of strings, but here it is a single string.styleUrls is correctly an array; selector is valid; template is optional.styles should be an array of strings, not a single string -> Option Astyles = array of strings [OK]styles, even if one style [OK]stylesstyleUrls typetemplate is mandatorystyles apply only to that component and are quick to edit without creating files.styles array for quick, component-specific changes -> Option Astyles [OK]Pass the test and this pattern moves unknown