【发布时间】:2021-08-25 16:14:01
【问题描述】:
根据 Angular 文档,host-context() 选择器正在搜索组件视图范围之外的匹配项。
所以我很困惑。我在 stackblitz 中尝试过,我发现即使在同一个组件中应用了该类,也存在匹配项。我做错了吗?
【问题讨论】:
标签: angular sass css-selectors
根据 Angular 文档,host-context() 选择器正在搜索组件视图范围之外的匹配项。
所以我很困惑。我在 stackblitz 中尝试过,我发现即使在同一个组件中应用了该类,也存在匹配项。我做错了吗?
【问题讨论】:
标签: angular sass css-selectors
:host-contexts 检查与 :host 相同的宿主元素上的类,然后检查你所知道的祖先。所以你的测试工作正常。请不要忘记 CSS 属性颜色是继承给子级的。
【讨论】:
您在根组件样式本身中定义了host-context,并且您传递的上下文在您使用它时是不一样的。
顾名思义host-context,这个伪选择器中的样式在匹配父元素的上下文时被应用。让我们通过一个例子来理解这一点。
假设,您有一个按钮组件,您希望根据应用到它的父元素的主题来设置主题。这里的上下文是父元素的类,需要在可主题化的按钮组件中定义宿主上下文,以便根据父元素的上下文应用主题:
主题按钮组件示例:
@Component({
selector: 'themeable-button',
template: `
<button class="btn btn-theme">Themeable Button</button>
`,
styles: [`
:host-context(.red-theme) .btn-theme {
background: red;
}
:host-context(.blue-theme) .btn-theme {
background: blue;
}
`]
})
export class ThemeableButtonComponent {
}
如您所见,host-context pueudo 类已在此组件的样式中定义,它采用不同的上下文(.red-theme 和 .blue-theme)。 现在根据托管此主题组件的父元素,将决定其背景颜色:
例如:
<div class="blue-theme"> // context here is blue-theme and hence the color of this button will be blue
<themeable-button></themeable-button>
</div>
<div class="red-theme">
<themeable-button></themeable-button>
</div>
<div class="no-theme"> // This won't have any color as no-theme is not a valid context defined in themeable button component.
<themeable-button></themeable-button>
</div>
检查这个Stackblitz,我有这个例子。
【讨论】: