Angular 2:如何设置组件的主机元素?

Rav*_*ati 169 css css-selectors angular-components angular

我在Angular 2中有一个名为my-comp的组件:

<my-comp></my-comp>
Run Code Online (Sandbox Code Playgroud)

如何在Angular 2中设置此组件的主机元素的样式?

在Polymer中,您将使用":host"选择器.我在Angular 2中尝试过它.但它不起作用.

:host {
  display: block;
  width: 100%;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

我也尝试使用组件作为选择器:

my-comp {
  display: block;
  width: 100%;
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

这两种方法似乎都不起作用.

谢谢.

Gün*_*uer 265

有一个错误,但在此期间修复了.:host { }现在工作正常.

也支持

  • :host(selector) { ... }用于selector匹配主机元素上的属性,类,...
  • :host-context(selector) { ... }用于selector匹配父组件上的元素,类,...

  • selector /deep/ selector(别名selector >>> selector不适用于SASS)样式要跨元素边界匹配

另请参阅将外部css样式加载到Angular 2 Component中

/deep/>>>不影响通过在Chrome中被弱化了相同的选择组合程序.
Angular模拟(重写)它们,因此不依赖于支持它们的浏览器.

这也是为什么/deep/并且>>>不能使用ViewEncapsulation.Native本机影子DOM并依赖于浏览器支持的原因.


pre*_*pic 33

我找到了一个解决方案,如何设置组件元素的样式.我没有找到任何文档如何工作,但您可以将属性值放入组件指令中,在'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;
}
Run Code Online (Sandbox Code Playgroud)

更新:正如GünterZöchbauer所说,有一个错误,现在你可以在css文件中设置主机元素的样式,如下所示:

:host{ ... }
Run Code Online (Sandbox Code Playgroud)

  • 不,在`stylesUrl`文件中通过`host {}`进行样式设置不起作用.需要`:host`. (4认同)

ale*_*ods 11

Check out this issue. I think the bug will be resolved when new template precompilation logic will be implemented. For now I think the best you can do is to wrap your template into <div class="root"> and style this div:

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

See this plunker


Xqu*_*ick 9

在组件中,如果要使用某些常规样式,可以将.cl​​ass添加到主机元素中.

export class MyComponent{
     @HostBinding('class') classes = 'classA classB';
Run Code Online (Sandbox Code Playgroud)


Pet*_*kou 5

对于希望为a的子元素设置样式的任何人,:host这里都是如何使用的示例::ng-deep

:host::ng-deep <child element>

例如 :host::ng-deep span { color: red; }

正如其他人所说/deep/的那样