角度 2 组件作用域样式



组件范围的样式 - 如何根据它们在站点中的位置以不同的方式设置样式,但仍保持样式的作用域?假设我使用我们在本课程中构建的"心形"项目,并且我想在左侧有很多填充,但前提是我将这个组件嵌套在我们构建的 Twitter 列表中......但是如果我在其他地方有这个心脏组件,我不想有这个填充 - 最好的方法是什么?每个场景的样式是否可以限定为此组件?

/*
style below are in the heart.styles.css
so these are scoped to heart component.
This acts like global style for this component and 
will apply no matter if it is nested in another component
how do you override this style if you don't want the padding
when it would be nested in another component lets say??
I have tried using the parent component css to override
but of course it wont work due to the scoping...and I don't
want to have some styles scoped and in one file and other styles
that aren't scoped because they have to sit outside the 
component
You will end up with css all over the place with no idea
and potential scope/specificity issues??
*/
.heart {margin: 0.1em 0 0 1.7em;}

我可能对此很愚蠢,但这对我来说并不明显

:host-context选择器执行此操作

:host-context(twitter) .heart {
  margin: 0.1em 0 0 1.7em;
}

当元素是 <twitter> 元素的后代时,此样式将应用于具有类 heart 的元素。

您有两种选择,具体取决于是要"向上查找"还是"向下查看"组件树:

  • Up - 使用 :host-context() 伪类选择器根据组件视图之外的某些条件应用样式(查找组件树)。 您指定一个组件、元素或类,Angular 将在组件主机元素的任何祖先中查找它,一直到文档根目录。如果找到匹配项,则 CSS 样式将应用于组件的视图。 @Günter在他的回答中已经提供了一个例子:
    :host-context(twitter) .heart { ... }

  • 向下 - 使用/deep/>>>选择器将样式通过组件树向下应用于所有子组件视图。 例如,将其添加到父/twitter组件:
    :host /deep/ .heart { ... }

最新更新