如何从父组件的css文件中设置子组件? [英] How to style child components from parent component's css file?

查看:858
本文介绍了如何从父组件的css文件中设置子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父组件:

<parent></parent>

我想使用子组件填充此组:

And I want to populate this group with child components:

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

父模板:

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

子模板:

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

由于 child 是两个独立的组件,它们的样式被锁定到自己的范围。

Since parent and child are two seperate components, their styles are locked to their own scope.

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

In my parent component I tried doing:

.parent .child {
  // Styles for child
}

.child 样式未应用于

But the .child styles are not getting applied to the child components.

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

I tried using styleUrls to include the parent's stylesheet into child component to solve the scope issue:

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

但这没有帮助,也尝试了另一种方法通过将样式表取到

But that didn't help, also tried the other way by fetching the child stylesheet into parent but that didn't help either.

那么,如何对包含在父组件中的子组件进行样式?

So how do you style child components that are included into a parent component?

推荐答案

您可以使用封装模式和/或穿透CSS组合器> ;>,/ 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文件中设置子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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