css - 应用来自父项的样式

标签 css angular angular2-directives

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

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

以便最终输出“Some text”是粗体 3em 大小?

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

最佳答案

  • 设置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>

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

关于css - 应用来自父项的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077722/

相关文章:

jquery - addClass 无法正常工作

html - 简单的 css 仅在 anchor 上应用背景颜色

html - 模板字段宽度在 asp.net 的 GridView 中没有增加

javascript - 有人可以帮我找到带有链接的 ng-contents 的定位器吗?

angular - 在另一个指令的主机中使用指令

html - Angular2 和 W3C HTML 验证

javascript - 当其他元素出现和消失时平滑地改变 HTML 元素位置的通用方法

node.js - 无法在 ubuntu 16.04 的 80 端口运行我的 Node 应用程序

angular - 如何使用 Angular2 将数据发送到 ASP.NET Controller

angular - 如何在自定义元素上实现 ngModel?