Skip to the workspace
Pebellslearn by building
Components  ›  Lesson

Templates, Styles and Encapsulation

Template 12 minA component's template and styles can be written inline or in separate files, and by default Angular scopes the styles so they only affect that component's own template.

angular / Templates, Styles and Encapsulation

Explore each scene at your own pace.

01 · The rule

The rule

Templates, Styles and Encapsulation

PlantCard now has a template and a stylesheet. As Greenhouse grows, dozens of components will each have an h3 rule. If every rule applied to the whole page, the last one loaded would win and the design would fall apart. Angular prevents that by default.

The rule

A component's styles stay home; global styles live in styles.css.

First, where the HTML and CSS live. Short ones can sit inline; longer ones go in their own files:

@Component({
  selector: 'app-plant-card',
  templateUrl: './plant-card.html',
  styleUrl: './plant-card.css',
})
export class PlantCard {}

Use exactly one of template or templateUrl. For CSS, styles holds inline CSS and styleUrl (or styleUrls for a list) points at files.

Now the scoping. By default Angular uses emulated encapsulation. It stamps every element in the component's template with a generated attribute, such as _ngcontent-abc-1, and rewrites each selector to require it. So h3 { color: seagreen; } becomes, in effect, h3[_ngcontent-abc-1], which only matches this component's headings.

Two extra tools:

  • :host styles the component's own tag, <app-plant-card>, from inside: :host { display: block; border: 1px solid #ccc; }.
  • encapsulation in the metadata changes the mode:
import { ViewEncapsulation } from '@angular/core';

@Component({
  // ...
  encapsulation: ViewEncapsulation.None,
})
Mode Effect
Emulated (default) Styles scoped with generated attributes
None Styles become global and can hit any element
ShadowDom Uses the browser's real Shadow DOM
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.