从父级应用样式

Sou*_*mya 12 css angular2-directives angular

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

<div class="frame">
  <span class="user-defined-text">{{text}}</span>
</div>
<style>
  span { font-size: 3em; }
  .frame { ... }
</style>
Run Code Online (Sandbox Code Playgroud)

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

<custom-component [text]="'Some text'">
<style>custom-component { font-weight: bold; }</style>
Run Code Online (Sandbox Code Playgroud)

所以最终输出"Some text"是粗体还是 3em大小?

更好的是有一种方法来获取主机元素的计算样式,例如,我可以将background-color主机的主机应用于border-color模板中的某个元素吗?

Gün*_*uer 21

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

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

<custom-component class="someClass"></custom-component>
Run Code Online (Sandbox Code Playgroud)

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


Mik*_*ike 18

我知道这是旧的,但我觉得这应该更加明显.您可以使用/deep/选择器将样式向下强制通过子组件树到所有子组件视图中.在/deep/选择工作的嵌套组件的任何深度,并同时适用于儿童观和成分含量的孩子.

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

parent.css

/deep/ .class {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

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

  • / deep /在聚合物和Chrome中被弃用(可能很快就会出现角度).并且必须仅使用**模拟视图封装**. (3认同)
  • 在Angular 4.3之前,使用/ deep /或>>>代替:: ng-deep.浏览器已弃用这两种表示法,因此:: ng-deep现在是临时解决方法.https://alligator.io/angular/styles-between-components-angular/ (2认同)