Angular:host <selector>不起作用

时间:2017-09-08 10:09:41

标签: angular

如果组件有活动,我想设置我的组件的样式。但它没有用。

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>

<小时/> 但是,如果我删除app.comonent.html文件和thread.component.css中的活动类。 完美无缺。

thread.component.html

<div>thread works!</div>

thread.component.css

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

app.component.html

<app-thread></app-thread>

3 个答案:

答案 0 :(得分:3)

来自docs

  

使用:host伪类选择器来定位元素中的样式   托管组件(而不是目标元素)   组件的模板)。

所以

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

将为整个主机设置样式,因此您的元素将继承该样式。

在这里设置一个类样式.active但是:不考虑主机。

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

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

答案 1 :(得分:0)

:host用于向组件本身添加样式,而不向其内部元素添加样式。

:host
{
   background-color: red;
}

将红色背景整体应用于角度分量。

现在:host(.active)仅在组件上具有活动类时才用于向其添加样式。

答案 2 :(得分:0)

如果组件定义中有 :host

encapsulation: ViewEncapsulation.None 将不会生效,如下所示。

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  encapsulation: ViewEncapsulation.None
})
相关问题