据我了解:host-context
用于根据父级的选择器应用样式。
让我们考虑一个规则,如下所示:
:host-context(.red-theme) { background-color: red; }
同样可以使用 :host 选择器作为 folows 编写:
.red-theme :host { background-color: red; }
那么host-context
明确要求什么?
如果要设置组件自定义 HTML 元素本身的样式,请使用:host
。
当您还希望让组件应用样式并考虑呈现组件的上下文时,将使用 as:host-context
。
例如,您可以执行以下操作:(使用host-context
)
<div class="red-theme">
<app-component></app-component>
</div>
哪里app-component
<button class="btn btn-theme">Button</button>
并且定义了组件样式:
:host-context(.red-theme) .btn-theme {
background: red;
}
如果您希望在 Web 应用程序上有多个替代主题,则非常有用。
:host
和:host-context
不是Angular功能,而是CSS功能。
在 stackblitz.com/edit/angular-z3xxtu 提供的演示中,Angular 组件被合并到 DOM 中,并允许像.parent :host .child { color: red; }
这样的普通旧 CSS 选择器结构。
当使用Webcomponents和ShadowDOM时,这种情况会发生变化。
ShadowDOM 充当屏障并封装包含的标记和样式,因此.parent
不能在:host
上设置样式,反之亦然。注意不能不完全正确,请参阅::part
和CSS Custom Properties
。
对于像<parent> <my-component> ShadowDOM <child>
这样的结构,上面的CSS规则不再有效,需要:host-context(.parent)
(可以读作.parent :host
)。可悲的是,截至 2023 年 1 月 10 日,这在 Firefox 和 Safari 中不起作用。
在上面的演示中,:host-context(.red) { color: red; }
和.red :host { color: red; }
产生相同的输出,因为不涉及ShadowDOM。最重要的是,Angular 将 CSS 中的无效.test :host
转换为.test [_nghost-some-id]
这是一个有效的CSS 选择器。