Angular2组件的样式未在封装的子组件中继承 [英] Angular2's component's styles are not inherited in the encapsulated child component

查看:119
本文介绍了Angular2组件的样式未在封装的子组件中继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写两个组件-ComponentAComponentB,其中ComponentA封装了ComponentB.他们两个都有一个p标记.在我的ComponentA中,我正在@Component装饰器中编写样式:p { color:red }. ComponentAp更改为红色,但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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆