如何在Angular 2中使用样式标签中的组件变量?
我有一个角2组件为我的头,我喜欢颜色取决于用户的设置。因此,我想分配一个背景和字体颜色。虽然我知道如何将属性绑定到元素,但我不知道如何在样式标记中使用。
对样式使用属性绑定效果很好,但是这会对几个子元素造成很大影响,特别是当它们嵌套在其他子组件中时。[ngStyle]=属性也只对单个元素起作用。
<header id="header" [style.background-color]="changeBackground()">
<div>
Some Text
<a href="asdf">Some Link</a>
<subcomponent></subcomponent>
</div>
<div> ... a lot mor stuff </div>
</header>
因此,我想补充一些内容
<style>
#header, #header a {
color: {{mycolor}};
}
</style>
到html模板。然而,这并不起作用
类似的问题还没有回答这个问题,只展示属性绑定作为一个解决方案:
在我看来,你只是在创建一个叫做“子组件”的新组件,为什么不这样做呢?
Subcomponent.ts:
import { Component } from '@angular/core';
@Component({
selector: 'subcomponent',
templateUrl: './subcomponent.html',
})
export class SubComponent {
mycolor = 'blue';
}
subcomponent.html:
<style>
#header, #header a {
color: {{mycolor}};
}
</style>