htmlcssangularangular-components

Angular :host <selector> is not working


I want to style my component if it has a class active. But it doesn't work.

thread.component.html

<div>thread works!</div>

thread.component.css

:host .active {
  display: block;
  border: 1px solid white;
}

app.component.html

<app-thread class="active"></app-thread>


However, if I remove active class in app.comonent.html file and thread.component.css. It works perfectly fine.

thread.component.html

<div>thread works!</div>

thread.component.css

:host {
  display: block;
  border: 1px solid white;
}

app.component.html

<app-thread></app-thread>

Solution

  • From the docs:

    Use the :host pseudo-class selector to target styles in the element that hosts the component (as opposed to targeting elements inside the component's template).

    So

    :host {
      display: block;
      border: 1px solid white;
    }
    

    will set the style for the whole host, so your element will just inherit of that style.

    But here you are targetting a class .active inside :host:

    // Any element with class "active", that is inside :host .
    // Same as ":host *.active".
    :host .active {
      display: block;
      border: 1px solid white;
    }
    

    Do instead:

    // :host when it has the class "active".
    :host(.active) {
      display: block;
      border: 1px solid white;
    }
    

    And be careful to NOT set

      encapsulation: ViewEncapsulation.None
    

    in the component code