如何从父组件的 CSS 文件中设置子组件的样式?

新手上路,请多包涵

我有一个父组件:

 <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 是两个独立的组件,因此它们的样式被锁定在自己的范围内。

在我的父组件中,我尝试做:

 .parent .child {
  // Styles for child
}

但是 .child 样式并未应用于 child 组件。

我尝试使用 styleUrlsparent 的样式表包含到 child 组件中来解决范围问题:

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

但这没有帮助,还尝试了另一种方法,将 child 样式表获取到 parent 但这也没有帮助。

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

原文由 Chrillewoodz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

更新 - 最新方式

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

最后更新

Angular 4.3.0 到现在(Angular 12.x),所有穿孔的 css 组合器都被弃用了。 Angular 团队引入了一个新的组合 ::ng-deep 如下图,

演示: https ://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview

 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>
    `


老路

您可以使用 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>
`

原文由 micronyks 发布,翻译遵循 CC BY-SA 4.0 许可协议

您不应该使用 ::ng-deep ,它已被弃用。在 Angular 中,从父组件更改子组件样式的正确方法是使用 encapsulation (阅读下面的警告以了解其含义):

 import { ViewEncapsulation } from '@angular/core';

@Component({
    ....
    encapsulation: ViewEncapsulation.None
})

然后,您将能够在不需要 ::ng-deep 的情况下修改组件的 css

 .mat-sort-header-container {
  display: flex;
  justify-content: center;
}

警告:这样做将使您为该组件编写的所有 css 规则成为全局规则。

为了将你的 css 范围限制在这个组件和他的孩子身上,添加一个 css 类到你的组件的顶部标签并将你的 css 放在这个标签“内部”:

模板:

 <div class='my-component'>
  <child-component class="first">First</child>
</div>,

文件:

 .my-component {
  // All your css goes in there in order not to be global
}

原文由 Tonio 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题