Angular:host <selector>不起作用

das*_*dsa 7 angular

如果它有一个活动的类,我想设置我的组件的样式.但它不起作用.

thread.component.html

<div>thread works!</div>
Run Code Online (Sandbox Code Playgroud)

thread.component.css

:host .active {
  display: block;
  border: 1px solid white;
}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<app-thread class="active"></app-thread>
Run Code Online (Sandbox Code Playgroud)


但是,如果我删除app.comonent.html文件和thread.component.css中的活动类.它工作得很好.

thread.component.html

<div>thread works!</div>
Run Code Online (Sandbox Code Playgroud)

thread.component.css

:host {
  display: block;
  border: 1px solid white;
}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<app-thread></app-thread>
Run Code Online (Sandbox Code Playgroud)

Wan*_*ker 25

:hostencapsulation: ViewEncapsulation.None如果您在组件的定义中有如下所示的内容,则不会生效。

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
  encapsulation: ViewEncapsulation.None
})
Run Code Online (Sandbox Code Playgroud)


Veg*_*ega 8

文档

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

所以

:host {
  display: block;
  border: 1px solid white;
}
Run Code Online (Sandbox Code Playgroud)

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

在这里,您正在设置类样式 .active 但不考虑 :host 。

:host .active {
  display: block;
  border: 1px solid white;
}
Run Code Online (Sandbox Code Playgroud)

:host(.active) {
  display: block;
  border: 1px solid white;
}
Run Code Online (Sandbox Code Playgroud)