Skip to main content

Command Palette

Search for a command to run...

Styling the host element in Angular

Updated
•1 min read•View as Markdown

Styling the host element in Angular can be done using the :host selector in the component's styles.

This example demonstrates how to encapsulate styles within a component and apply them directly to the host element using the :host pseudo-class.

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    <div>
      <p>Content inside my component</p>
    </div>
  `,
  styles: [
    `
      :host {
        display: block;
        border: 2px solid black;
        padding: 10px;
        background-color: lightblue;
      }

      :host:hover {
        background-color: lightcoral;
      }
    `
  ]
})
export class MyComponent {}

Explanation

  • :host: The :host selector is used to apply styles to the host element itself, which is <app-my-component> in this case.

  • display: block: custom elements are not display block by default.

Example

Stackblitz example