在Angular 2中,您可以在组件的模板中包含样式表。由于Angular 2的View Encapsulation,样式仅适用于包含元素。
有没有办法为组件的主标签设置样式而不会放置周围的<div class="component-wrapper"></div>
?
示例plnkr:http://plnkr.co/edit/rANAsR1h9ERBIZV6wuJ8
它有一个外部css文件,为<app>
标记添加边框和填充,模板尝试设置背景颜色。
答案 0 :(得分:22)
您有两个选择
host
属性@Component({
selector : 'my-component',
host : {
'[style.color]' : "'red'",
'[style.background-color]' : 'backgroundColor'
}
})
class MyComponent {
backgroundColor: string;
constructor() {
this.backgroundColor = 'blue';
}
}
styles
属性和:host
@Component({
selector : 'my-component',
styles : [`
:host {
color: red;
background-color: blue;
}
`]
})
class MyComponent {}
注意使用:host
和ViewEncapsulation.None
时有odd behavior。
这是一个plnkr,其中包含两个备选方案的简单示例。
答案 1 :(得分:0)
最简单的方法!?
在 your.component.css 中:
:host {
background-color: blue;
}