Components in Depth: Metadata, Styles and Encapsulation
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 { }
| Option | Purpose |
|---|---|
selector | Tag name used in HTML |
imports | Components, directives, pipes used in the template |
template / templateUrl | Inline or external HTML |
styles / styleUrl | Component CSS |
changeDetection | When Angular rechecks this component (OnPush recommended) |
encapsulation | How styles are isolated |
host | Attributes, 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.
ViewEncapsulation | Behavior |
|---|---|
Emulated (default) | Styles are scoped using generated attributes |
None | Styles become global |
ShadowDom | Uses 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.

