Angular 2组件样式本身可以吗?

时间:2016-01-11 22:10:30

标签: angular

在Angular 2中,您可以在组件的模板中包含样式表。由于Angular 2的View Encapsulation,样式仅适用于包含元素。

有没有办法为组件的主标签设置样式而不会放置周围的<div class="component-wrapper"></div>

示例plnkr:http://plnkr.co/edit/rANAsR1h9ERBIZV6wuJ8

它有一个外部css文件,为<app>标记添加边框和填充,模板尝试设置背景颜色。

2 个答案:

答案 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 {}

注意使用:hostViewEncapsulation.None时有odd behavior

这是一个plnkr,其中包含两个备选方案的简单示例。

答案 1 :(得分:0)

最简单的方法!?

在 your.component.css 中:

:host {
    background-color: blue;
}