Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular :host <selector> is not working

Tags:

angular

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>
like image 337
dasfdsa Avatar asked Sep 08 '17 10:09

dasfdsa


2 Answers

:host will not take effect if you have encapsulation: ViewEncapsulation.None in the component's definition as shown below.

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  encapsulation: ViewEncapsulation.None
})
like image 182
Wand Maker Avatar answered Oct 03 '22 10:10

Wand Maker


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.

Here you are setting a class style .active but :host is not taken in consideration.

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

Do

:host(.active) {
  display: block;
  border: 1px solid white;
}
like image 21
Vega Avatar answered Oct 03 '22 09:10

Vega