简体   繁体   English

Angular 2 Component范围样式

[英]Angular 2 Component scoped styles

Component scoped styles - how to style things differently depending on where they are in the site but still keep the styles scoped? 组件范围样式 - 如何根据站点中的位置设置不同的样式,但仍然保留样式作用域? Lets say I use the "heart like" item that we built in this course and I want to have lots of padding on the left but only if I nest this component within the twitter list that we built...but I don't want to have this padding if I have this heart component elsewhere - whats the best way to do this?? 让我说我使用我们在本课程中构建的“像心脏”项目,我想在左边有很多填充,但只有我将这个组件嵌入我们构建的推文列表中...但我不想要如果我在其他地方有这个心脏组件,有这个填充 - 最好的方法是什么? And can the styles for each scenario be scoped to just this component?? 并且每个场景的样式是否可以限定为此组件?

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

I am probably being dumb about this but it is not obvious to me 我可能对此很愚蠢,但这对我来说并不明显

The :host-context selector does this :host-context选择器执行此操作

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

When the element is a descendant of the <twitter> element, this style is applied to elements with class heart . 当元素是<twitter>元素的后代时,此样式将应用于具有类heart元素。

You have two choices, depending on whether you want to "look up", or "look down" the component tree: 您有两种选择,具体取决于您是要“查找”还是“向下看”组件树:

  • Up - Use the :host-context() pseudo-class selector to apply styles based on some condition outside a component's view (look up the component tree). Up - 使用:host-context()伪类选择器根据组件视图外的某些条件应用样式(查找组件树)。 You specify a component, element or class and Angular will look for it in any ancestor of the component's host element, all the way up to the document root. 您指定组件,元素或类,Angular将在组件的host元素的任何祖先中查找它,一直到文档根目录。 If it finds a match, the CSS style is applied to the component's view. 如果找到匹配项,则CSS样式将应用于组件的视图。 @Günter already provided an example of this in his answer: @Günter已经在他的回答中提供了一个例子:
    :host-context(twitter) .heart { ... }

  • Down - Use the /deep/ or >>> selector to apply a style down through the component tree to all child component views. 向下 - 使用/deep/>>>选择器将组件树中的样式向下应用于所有子组件视图。 Eg, add this to the parent/ twitter component: 例如,将其添加到父/ twitter组件:
    :host /deep/ .heart { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM