Back to Angular

Component Styling

skills/dev-skills/angular-developer/references/component-styling.md

22.0.0-next.102.5 KB
Original Source

Component Styling

Angular components can define styles that apply specifically to their template, enabling encapsulation and modularity.

Defining Styles

Styles can be defined inline or in separate files.

ts
@Component({
  selector: 'app-photo',
  // Inline styles
  styles: `
    img {
      border-radius: 50%;
    }
  `,
  // OR external file
  styleUrl: 'photo.component.css',
})
export class Photo {}

View Encapsulation

Every component has a view encapsulation setting that determines how styles are scoped.

ModeBehavior
Emulated (Default)Scopes styles to the component using unique HTML attributes. Global styles can still leak in.
ShadowDomUses the browser's native Shadow DOM API to isolate styles completely.
NoneDisables encapsulation. Component styles become global.
ExperimentalIsolatedShadowDomStrictly guarantees that only the component's styles apply.

Usage

ts
import { ViewEncapsulation } from '@angular/core';

@Component({
  ...,
  encapsulation: ViewEncapsulation.None,
})
export class GlobalStyled {}

Special Selectors

:host

Targets the component's host element (the element matching the component's selector).

css
:host {
  display: block;
  border: 1px solid black;
}

:host-context()

Targets the host element based on some condition in its ancestry.

css
/* Apply styles if any ancestor has the 'theme-dark' class */
:host-context(.theme-dark) {
  background-color: #333;
}

::ng-deep

Disables view encapsulation for a specific rule, allowing it to "leak" into child components. Note: The Angular team strongly discourages the use of ::ng-deep. It is supported only for backwards compatibility.

Styles in Templates

You can use <style> elements directly in a component's template. View encapsulation rules still apply.

html
<style>
  .dynamic-class {
    color: red;
  }
</style>
<div class="dynamic-class">Hello</div>

External Styles

Using <link> or @import in CSS is treated as external styles. External styles are not affected by emulated view encapsulation.