12

假设我有一个带有此模板的组件:

<div class="frame">
  <span class="user-defined-text">{{text}}</span>
</div>
<style>
  span { font-size: 3em; }
  .frame { ... }
</style>

如何合并应用于组件的样式,例如

<custom-component [text]="'Some text'">
<style>custom-component { font-weight: bold; }</style>

以便最终输出“某些文本”既粗体是3em 大小?

有没有更好的方法来获取宿主元素的计算样式,例如,我可以将background-color宿主的 应用到border-color模板中某些元素的 ?

4

4 回答 4

21
  • 设置encapsulation: ViewEncapsulation.None为允许应用来自外部的样式。
import {Component, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'custom-component',
  encapsulation: ViewEncapsulation.None
})
export class Custom {
  • 用于styleUrl结合主机选择器添加 CSS 文件
:host(.someClass) {
      background-color: blue;
}

<custom-component class="someClass"></custom-component>

根据添加到元素的类来应用样式。

于 2016-01-29T06:45:11.940 回答
18

我知道这是旧的,但我觉得这应该更明显。您可以使用/deep/选择器将样式强制通过子组件树向下进入所有子组件视图。选择/deep/器适用于任何深度的嵌套组件,它适用于组件的视图子项和内容子项。

我觉得这更清洁,更容易实现。

父.css

/deep/ .class {
    background-color: red;
}

https://angular.io/docs/ts/latest/guide/component-styles.html

于 2016-11-07T19:19:40.293 回答
0

关于 CSS,组件支持 shadow DOM。这意味着他们的风格是孤立的。默认模式是隔离的。所以你需要在组件中定义 CSS 样式(styles 属性)。

您还可以将封装模式更改为ViewEncapsulation.None. 这样你的组件就可以看到父组件的样式:

@Component({
  selector: 'child',
  encapsulation: ViewEncapsulation.None,
  (...)
})
export class MyComponent {
  (...)
}

希望它可以帮助你,蒂埃里

于 2016-01-29T06:44:46.487 回答
0

使用:host伪类选择器来设置 any 的样式<custom-component>

我们不能通过使用类将 css 样式写入自定义元素。

例子

<custom-component class="custom-comp" [text]="'Some text'">

.custom-comp {
  font-weight: bold;
  color: green;
}

为此,我们可以使用 :host 选择器来设置如下样式

@Component({
  selector: 'custom-component',
  templateUrl: './custom-component.html',
  styleUrls: ['./custom-component.scss']
})

在 custom-component.scss

:host {
  font-weight: bold;
  color: green;
}

您可以在 Angular4 的官方文档中阅读更多关于:host元素样式的信息

于 2017-09-01T10:25:41.800 回答