我在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 > /deep/:

将以下内容添加到parent.component.less文件

:host {
    /deep/ app-child-component {
       //your child style
    }
}

用你的子选择器替换app-child-component

其他回答

看看这个问题。我认为当新的模板预编译逻辑实现时,这个错误将得到解决。现在我认为你能做的最好的是包装你的模板到<div class="root">和样式这个div:

@Component({ ... })
@View({
  template: `
    <div class="root">
      <h2>Hello Angular2!</h2>
      <p>here is your template</p>
    </div>
  `,
  styles: [`
    .root {
      background: blue;
    }
  `],
   ...
})
class SomeComponent {}

看这个活塞

在你的组件中,如果你想要应用一些通用的样式,你可以将.class添加到你的主机元素中。

export class MyComponent{
     @HostBinding('class') classes = 'classA classB';

对于想要为:host的子元素设置样式的人,这里有一个如何使用::ng-deep的示例

:host::ng-deep <子元素>

例如:host::ng-deep span{颜色:红色;}

正如其他人所说/深/是不赞成的

我已经找到了一个解决方案如何样式只是组件元素。我没有找到它是如何工作的任何文档,但你可以把属性值放在组件指令中,在'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{ ... }

试试:host > /deep/:

将以下内容添加到parent.component.less文件

:host {
    /deep/ app-child-component {
       //your child style
    }
}

用你的子选择器替换app-child-component