我在Angular 2中有一个名为my-comp的组件:
<my-comp></my-comp>
在Angular 2中如何为这个组件的宿主元素设置样式?
在Polymer中,您将使用“:host”选择器。我在Angular 2中尝试过。但这并不奏效。
:host {
display: block;
width: 100%;
height: 100%;
}
我还尝试使用组件作为选择器:
my-comp {
display: block;
width: 100%;
height: 100%;
}
这两种方法似乎都不管用。
谢谢。
我已经找到了一个解决方案如何样式只是组件元素。我没有找到它是如何工作的任何文档,但你可以把属性值放在组件指令中,在'host'属性下,像这样:
@Component({
...
styles: [`
:host {
'style': 'display: table; height: 100%',
'class': 'myClass'
}`
})
export class MyComponent
{
constructor() {}
// Also you can use @HostBinding decorator
@HostBinding('style.background-color') public color: string = 'lime';
@HostBinding('class.highlighted') public highlighted: boolean = true;
}
更新:
正如Günter Zöchbauer提到的,有一个错误,现在你可以在css文件中设置host元素的样式,就像这样:
:host{ ... }