由 DOM 属性 _ngcontent-\* 与 _nghost-\* 引起的 Angular2 样式问题

新手上路,请多包涵

我对 scss 和 cli 有疑问: angular 在运行时将属性 _nghost-fyw-1 添加到应用程序标签(组件)。同时,它向我的 CSS 中添加了一个名为 _ngcontent-fyw-1 的属性选择器,这当然是行不通的。

你知道我如何改变这种行为/避免它吗?

PS:它也适用于常规 css。

我的组件 .scss 文件如下所示:

 my-comp {
  h1 {
    background-color: red;
  }
}

原文由 wzr1337 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 348
1 个回答

出色地,

我自己找到了答案。使用默认设置,您 不能 在组件 css 中提供包装 my-comp 元素选择器。

而是使用 * 元素选择器来影响嵌套在 my-comp 中的所有元素。否则,Angular 会将 my-comp 选择器视为附加元素,从而添加 _ng-content-* 属性,这在 DOM 中当然不存在。

另一种选择是为您的组件禁用 ViewEncapsulation - 请注意它只会影响组件 my-comp

 import {Component, ViewEncapsulation} from 'angular2/core'

@Component({
  selector: 'my-comp',
  encapsulation: ViewEncapsulation.None,
  ...
});

https://egghead.io/lessons/angular-2-controlling-how-styles-are-shared-with-view-encapsulation 完美解释了三种不同的设置模式。

原文由 wzr1337 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题