Angular 2 Component范围样式

时间:2016-06-02 15:44:27

标签: javascript css angular

组件作用域样式 - 如何根据站点中的位置设置不同的样式,但仍保留样式作用域?让我们说我喜欢"心脏就像#34;我们在这个课程中构建的项目,我想在左边有很多填充,但只有当我将这个组件嵌入我们构建的推文列表中时......但是如果我有这个填充,我不想要这个填充这个心脏成分在其他地方 - 最好的方法是什么?并且每个场景的样式是否可以限定为此组件?

/*
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;}

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

2 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:3)

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

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

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