Components in Depth: Metadata, Styles and Encapsulation

Angular 12 min min read Updated: Nov 16, 2026 Beginner
Components in Depth: Metadata, Styles and Encapsulation
Beginner Topic 1 of 7

The @Component Decorator

typescript @Component({ selector: 'app-user-card', imports: [], templateUrl: './user-card.html', styleUrls: ['./user-card.css'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.Emulated, host: { class: 'card', '[class.active]': 'isActive()', '(click)': 'toggle()' }, }) export class UserCard { }
OptionPurpose
selectorTag name used in HTML
importsComponents, directives, pipes used in the template
template / templateUrlInline or external HTML
styles / styleUrlComponent CSS
changeDetectionWhen Angular rechecks this component (OnPush recommended)
encapsulationHow styles are isolated
hostAttributes, classes and listeners on the component's own element

Selector Forms

typescript selector: 'app-card' // <app-card></app-card> (most common) selector: '[appHighlight]' // <div appHighlight> (attribute, for directives) selector: '.my-card' // <div class="my-card"> (rare)

Component Styles Are Private

css /* user-card.css */ h2 { color: crimson; } /* affects only h2 inside this component */ :host { display: block; border: 1px solid #ddd; padding: 12px; } /* the component element itself */ :host(.active) { border-color: green; } :host-context(.dark) h2 { color: white; }
How it works: Angular adds unique attributes such as _ngcontent-abc-c12 to elements and rewrites your CSS so it only matches this component. This is called emulated encapsulation and it is the default.
ViewEncapsulationBehavior
Emulated (default)Styles are scoped using generated attributes
NoneStyles become global
ShadowDomUses the browser's real Shadow DOM

Global Styles

Put site-wide CSS (fonts, resets, utility classes) in src/styles.css. It is listed in angular.json.

css /* src/styles.css */ :root { --primary: #0d6efd; } body { font-family: system-ui, sans-serif; margin: 0; }

CSS Variables for Themes

css /* component */ button { background: var(--primary); }
Reach into a child? Because styles are private, a parent cannot style the inside of a child. Use CSS variables, an input that adds a class, or ViewEncapsulation.None carefully. Avoid the old ::ng-deep, which is deprecated.

Host Bindings in Metadata

typescript @Component({ selector: 'app-tab', template: `<ng-content />`, host: { role: 'tabpanel', '[class.selected]': 'selected()', '(keydown.enter)': 'select()', }, }) export class Tab { selected = signal(false); select() { this.selected.set(true); } }

Conclusion

@Component describes selector, template, styles and behavior. Styles are scoped to the component by default; use :host, CSS variables and global styles.css for sharing.

Quick Summary: Selector + template + styles; styles are private; host for the element itself.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators