我有一个父零部件:

<parent></parent>

我想用子组件填充这个组:

<parent>
  <child></child>
  <child></child>
  <child></child>
</parent>

父模板:

<div class="parent">
  <!-- Children goes here -->
  <ng-content></ng-content>
</div>

子模板:

<div class="child">Test</div>

由于parentchild是两个独立的组件,因此它们的样式锁定在各自的范围内.

在我的父组件中,我try 执行以下操作:

.parent .child {
  // Styles for child
}

但这.child种样式并没有应用于child个组件.

我try 使用styleUrlsparent的样式表包含到child组件中,以解决范围问题:

// child.component.ts
styleUrls: [
  './parent.component.css',
  './child.component.css',
]

但这没有帮助,我还try 了另一种方法,将child样式表提取到parent中,但这也没有帮助.

那么,如何设置包含在父零部件中的子零部件的样式呢?

推荐答案

Update - Newest Way

如果可以避免的话,就不要这样做.正如Devon Sans在 comments 中指出的那样:这个功能很可能会被弃用.

上次更新

Angular 4.3.0年到现在(Angular 12.x),所有穿孔css组合器都被弃用.Angular团队推出了一款新的combinator 100,如下所示,

DEMO : 100

styles: [
    `
     :host { color: red; }
     
     :host ::ng-deep parent {
       color:blue;
     }
     :host ::ng-deep child{
       color:orange;
     }
     :host ::ng-deep child.class1 {
       color:yellow;
     }
     :host ::ng-deep child.class2{
       color:pink;
     }
    `
],



template: `
      Angular2                                //red
      <parent>                                //blue
          <child></child>                     //orange
          <child class="class1"></child>      //yellow
          <child class="class2"></child>      //pink
      </parent>      
    `

Old way

您可以使用encapsulation mode和/或piercing CSS combinators >>>, /deep/ and ::shadow

工作示例:http://plnkr.co/edit/1RBDGQ?p=preview

styles: [
    `
     :host { color: red; }
     :host >>> parent {
       color:blue;
     }
     :host >>> child{
       color:orange;
     }
     :host >>> child.class1 {
       color:yellow;
     }
     :host >>> child.class2{
       color:pink;
     }
    `
    ],

template: `
  Angular2                                //red
  <parent>                                //blue
      <child></child>                     //orange
      <child class="class1"></child>      //yellow
      <child class="class2"></child>      //pink
  </parent>      
`

Css相关问答推荐

如何以Angular 调整下拉控件的高度

VueJS CSS动画不会扩展到v-card/v-col之外

如何以Angular 将下拉面板的宽度与其文本框对齐

如何通过重复的网格区域来简化网格布局?

如何引用 SCSS 中的现有类?

如何减少弹性项目之间的差距

Flex & space-around 与内容相交

最多 2 行的 Flex 水平滚动

使用 node-sass 在压缩文件末尾添加 min.css 文件扩展名

在 css Select 器中匹配 unicode char

为什么标题中的特定 div 与 Odoo 13 中 PDF 中的页面重叠?

创建一条淡出/在各个方向变得透明的线

将 CSS 注入 Shadow 根.然而风格正在受到影响

如何在 Chrome 中模拟偏好 colored颜色 方案媒体查询?

纯 CSS 滚动动画

数据协议 URL 大小限制

删除行内块元素中大文本上方和下方的空白

打印html时在页面上打印页码

如何创建一个带点的
标签?

CSS中伪元素前的&是什么意思?