问题描述
限时送ChatGPT账号..我在 Angular 2 中有名为 my-comp 的组件:
I have component in Angular 2 called my-comp:
<my-comp></my-comp>
如何在 Angular 2 中设置此组件的宿主元素的样式?
How does one style the host element of this component in Angular 2?
在 Polymer 中,您将使用 ":host" 选择器.我在 Angular 2 中尝试过.但它不起作用.
In Polymer, You would use ":host" selector. I tried it in Angular 2. But it doesn't work.
:host {
display: block;
width: 100%;
height: 100%;
}
我也尝试使用组件作为选择器:
I also tried using the component as selector:
my-comp {
display: block;
width: 100%;
height: 100%;
}
这两种方法似乎都不起作用.
Both approaches don't seem to work.
谢谢.
推荐答案
有一个错误,但在此期间已修复.:host { }
现在工作正常.
There was a bug, but it was fixed in the meantime. :host { }
works fine now.
还支持
:host(selector) { ... }
用于 selector
匹配宿主元素上的属性、类、...:host-context(selector) { ... }
用于 selector
匹配元素、类、...在父组件上
:host(selector) { ... }
for selector
to match attributes, classes, ... on the host element
:host-context(selector) { ... }
for selector
to match elements, classes, ...on parent components
selector/deep/selector
(别名 selector >>> selector
不适用于 SASS)用于匹配样式元素边界
selector /deep/ selector
(alias selector >>> selector
doesn't work with SASS) for styles to match across element boundaries
更新:SASS 正在弃用 /deep/
.
Angular(TS 和 Dart)添加了 ::ng-deep
作为替代品,它也与 SASS 兼容.
UPDATE: SASS is deprecating /deep/
.
Angular (TS and Dart) added ::ng-deep
as a replacement that's also compatible with SASS.
UPDATE2: ::slotted
::slotted
现在被所有新浏览器支持,并且可以与 `ViewEncapsulation.ShadowDom
一起使用https://developer.mozilla/en-US/docs/Web/CSS/::slotted
UPDATE2: ::slotted
::slotted
is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom
https://developer.mozilla/en-US/docs/Web/CSS/::slotted
另见 将外部 css 样式加载到 Angular 2组件
/deep/
和 >>>
不受 Chrome 中已弃用的相同选择器组合器的影响.
Angular 模拟(重写)它们,因此不依赖于支持它们的浏览器.
/deep/
and >>>
are not affected by the same selector combinators that in Chrome which are deprecated.
Angular emulates (rewrites) them, and therefore doesn't depend on browsers supporting them.
这也是 /deep/
和 >>>
不能与启用原生阴影的 ViewEncapsulation.Native
一起使用的原因DOM 并取决于浏览器支持.
This is also why /deep/
and >>>
don't work with ViewEncapsulation.Native
which enables native shadow DOM and depends on browser support.
这篇关于Angular 2:如何为组件的宿主元素设置样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论