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

Rya*_*yan 14 angular

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

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

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

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

Eri*_*nez 26

你有两个选择

  • 使用host财产
@Component({
    selector : 'my-component',
    host : {
        '[style.color]' : "'red'", 
        '[style.background-color]' : 'backgroundColor'
    }
})
class MyComponent {
    backgroundColor: string;
    constructor() {
        this.backgroundColor = 'blue';
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 使用styles属性和:host
@Component({
    selector : 'my-component',
    styles : [`
        :host {
            color: red;
            background-color: blue;
        }
    `]
})
class MyComponent {}
Run Code Online (Sandbox Code Playgroud)

注意使用和时有一个奇怪的行为.:hostViewEncapsulation.None

这里有一个plnkr与两种选择简单的例子.

  • 是否可以在组件scss文件中编写主机样式? (2认同)

小智 17

最好的简单方法!

在你的.component.css中:

:host {
    background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)