如何在Angular 2中使用样式TAG中的组件变量?
我的标题有一个Angular 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模板。但是这不起作用
类似的问题尚未回答这个问题,只显示属性绑定作为解决方案:
答案 0 :(得分:0)
在我看来,你只是在创建一个名为“子组件”的新组件,为什么不这样做呢?
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>
答案 1 :(得分:-2)
添加
到@Component对象styles:[ `#header, #header a {
color: {{mycolor}};
}`]
例如:
@Component({
template: `<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>`,
styles: [ `#header, #header a {
color: {{mycolor}};
}`
`]
})
答案 2 :(得分:-2)
使用NgStyle,如本回答所述
https://stackoverflow.com/a/41903349
简而言之
<header id="header" [ngStyle]="getStyle()">
<div>
Some Text
<a href="asdf">Some Link</a>
<subcomponent></subcomponent>
</div>
<div> ... a lot mor stuff </div>
</header>
和
getStyle(): any {
return {"background-color" : this.changeBackgroundColor()};
}