Angular2组件的样式未在封装的子组件中继承 [英] Angular2's component's styles are not inherited in the encapsulated child component
问题描述
我正在编写两个组件-ComponentA
和ComponentB
,其中ComponentA
封装了ComponentB
.他们两个都有一个p
标记.在我的ComponentA
中,我正在@Component
装饰器中编写样式:p { color:red }
. ComponentA
的p
更改为红色,但ComponentB
的颜色保持黑色.
I am writing two components - ComponentA
and ComponentB
, where ComponentA
encapsulates ComponentB
. Both of them have a p
tag. In my ComponentA
, I am writing styles: p { color:red }
inside my @Component
decorator. The ComponentA
's p
is changed to red but ComponentB
's color remains black.
我认为这是一个需要解决的错误.
I think it's a bug which needs to be resolved.
推荐答案
样式封装(防止样式渗入或渗出组件)是Angular组件的主要功能.
Style encapsulation (preventing style from bleeding into or out of components) is a main feature of Angular components.
有多种选择可以实现您想要的
There are different options to achieve what you want
@Component({
selector: 'component-b',
styles: [`
p { color: red; }
`]
...
encapsulation: ViewEncapsulation.None
})
或者您可以更改CSS选择器以使用最近引入的(仅Angular2)阴影穿孔CSS组合器>>>
or you can change the CSS selector to cross component boundaries with the recently introduced (Angular2 only) shadow piercing CSS combinator >>>
@Component({
selector: 'component-b',
styles: [`
:host ::ng-deep p { color: red; }
`]
...
})
第二种方法适用于默认封装(ViewEncapsulation.Emulated
).
您不能将::ng-deep
(>>>
)与encapsulation: ViewEncapsulation.Native
一起使用.
从Chrome中删除了对>>>
(或等效的/deep/
)的支持,并且从未在其他浏览器中真正提供支持.
The 2nd approach works with the default encapsulation (ViewEncapsulation.Emulated
).
You can't use ::ng-deep
(>>>
) with encapsulation: ViewEncapsulation.Native
.
Support for >>>
(or the equivalent /deep/
) was removed from Chrome and never really supported in other browsers.
提示:
/deep/
在SASS上似乎比>>>
SASS不久前推出了::ng-deep
来支持此Angular功能(当从SASS中删除了对/deep/
的支持时)
hint:
/deep/
seems to work better with SASS than >>>
SASS introduced ::ng-deep
a while back to support this Angular feature (when support for /deep/
was removed from SASS)
这篇关于Angular2组件的样式未在封装的子组件中继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!