我有一个父组件:

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

由于父组件和子组件是两个独立的组件,它们的样式被锁定在自己的范围内。

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

.parent .child {
  // Styles for child
}

但是.child样式没有应用到子组件。

我尝试使用styleUrls将父组件的样式表包含到子组件中,以解决范围问题:

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

但这并没有帮助,我还尝试了另一种方法,将子样式表取到父样式表中,但这也没有帮助。

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


当前回答

实际上还有一个选择。这样比较安全。你可以使用ViewEncapsulation。但把你所有的组件样式放到它的标签(又名选择器)。但无论如何,总是喜欢一些全局风格加上封装风格。

下面是Denis Rybalka的例子:

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

@Component({
  selector: 'parent',
  styles: [`
    parent {
      .first {
        color:blue;
      }
      .second {
        color:red;
      }
    }
 `],
 template: `
    <div>
      <child class="first">First</child>
      <child class="second">Second</child>
    </div>`,
  encapsulation: ViewEncapsulation.None,
})
export class ParentComponent  {
  constructor() { }
}

其他回答

也有同样的问题,所以如果你在scss/sass中使用angular2-cli,使用'/deep/'而不是'>>>',最后的选择器还不支持(但适用于css)。

随着互联网的更新,我想到了一个解决方案。

首先是一些警告。

还是不要这么做。澄清一下,我不打算让子组件允许您对它们进行样式设置。SOC。如果你作为组件设计者想要允许这一点,那么你就拥有了更多的权力。 如果你的孩子没有生活在阴影中,那么这对你来说就行不通了。 如果你必须支持一个浏览器,不能有一个影子dom,那么这也不会为你工作。

首先,将子组件的封装标记为shadow,以便它在实际的shadow dom中呈现。其次,将part属性添加到希望允许父元素设置样式的元素中。在父组件样式表中,可以使用::part()方法进行访问

我发现如果你可以访问子组件代码,传递@INPUT变量会更简洁:

这个想法是,父进程告诉子进程它的外观状态应该是什么,而子进程决定如何显示这个状态。这是一个很好的建筑

SCSS道:

.active {
  ::ng-deep md-list-item {
    background-color: #eee;
  }
}

更好的方法:-使用选定的变量:

<md-list>
    <a
            *ngFor="let convo of conversations"
            routerLink="/conversations/{{convo.id}}/messages"
            #rla="routerLinkActive"
            routerLinkActive="active">
        <app-conversation
                [selected]="rla.isActive"
                [convo]="convo"></app-conversation>
    </a>
</md-list>

可悲的是/deep/选择器已弃用(至少在Chrome中) https://www.chromestatus.com/features/6750456638341120

简而言之,(目前)似乎没有长期的解决方案,除了以某种方式让你的子组件动态地设置样式。 你可以传递一个样式对象给你的孩子,并通过以下方式应用它: < div [attr.style] = " styleobject " > 或者如果你有一个特定的风格,你可以使用像这样的东西: < div [style.background-color] = " colorvar " >

更多与此相关的讨论: https://github.com/angular/angular/issues/6511

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

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

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

然后,你就可以修改组件的css,而不需要使用::ng-deep

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

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

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

模板:

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

Scss文件:

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