css - Angular 2 : How to style host element of the component?

标签 css angular css-selectors angular-components

我在 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 { } 现在工作正常。

还支持

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

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

    • 更新:SASS 正在弃用 /deep/
      Angular(TS 和 Dart)添加了 ::ng-deep 作为替代品,它也与 SASS 兼容。

    • UPDATE2: ::slotted ::slotted 现在受到所有新浏览器的支持,并且可以与 `ViewEncapsulation.ShadowDom
      一起使用 https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

另见 Load external css style into Angular 2 Component

/deep/>>> 不受 Chrome 中已弃用的相同选择器组合器的影响。
Angular 模拟(重写)它们,因此不依赖于支持它们的浏览器。

这也是为什么 /deep/>>> 不能与 ViewEncapsulation.Native 一起使用,后者启用原生影子 DOM 并依赖关于浏览器支持。

关于css - Angular 2 : How to style host element of the component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32853924/

相关文章:

css - :required or [required] CSS selector

css - TailWindCSS 最大高度

html - Opera 中 margin-bottom 的计算方式不同

angular - woff2、woff 和 ttf 文件未加载并给出 400 错误

angular - 带有Angular的Docker报错 “ERROR in No NgModule metadata found for ' AppModule'。”

html - css:目标是同一个类中的一个类

Python Scrapy 获取不到伪类 ":not()"

css - 添加带有元素 X、Y 坐标的工具提示

css - 如何在 Grails 中将字段标签放置在字段顶部而不是左侧

Angular Material 自定义主题 - 为什么 mat-palette 需要 4 个变量?