假设我有一个带有这个模板的组件:
<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/