Angular 2:如何为组件的宿主元素设置样式?

编程入门 行业动态 更新时间:2024-10-22 18:34:05
本文介绍了Angular 2:如何为组件的宿主元素设置样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-22 12:36:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:宿主   何为   样式   组件   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!