css - Angular:组件样式不会级联到子组件?

标签 css angular sass

在我的 app.component.html 中,我有以下工作类作业。

<body>
  <span class="test">SHABOO</span>
  <div class="container">
    <router-outlet></router-outlet>
  </div>
</body>

在 outlet 中,渲染了一个组件,它包含以下内容。

<span class="test">HAZAA</span>

我预计它会获得与第一个相同的样式,但该样式似乎并未向下级联到组件。这让我不确定我是否误解了样式在 Angular 中的父组件和子组件之间的行为方式。

我确保没有覆盖类的名称(以排除冲突的风险)。目前,我在每个组件中都放置了类似的 SCSS 代码块,这显然是一种不好的做法。

如果我 @import "../app.component.scss",样式就会开始。但我的印象是即使没有导入,样式也应该层叠。

最佳答案

Angular 组件使用view encapsulation .这是设计使然,组件可以跨应用程序重用。要将组件的样式视为全局,请将 View 封装模式设置为none(不推荐)。

不使用none,而是在Angular CLI styles section 中注册全局样式文件。 ,它是使用 styles.css 文件预先配置的。

Component CSS styles are encapsulated into the component's view and don't affect the rest of the application.

To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes:

  • ShadowDom view encapsulation uses the browser's native shadow DOM implementation (see Shadow DOM on the MDN site) to attach a shadow DOM to the component's host element, and then puts the component view inside that shadow DOM. The component's styles are included within the shadow DOM.

  • Native view encapsulation uses a now deprecated version of the browser's native shadow DOM implementation - learn about the changes.

  • Emulated view encapsulation (the default) emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view. For details, see Appendix 1.

  • None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

To set the components encapsulation mode, use the encapsulation property in the component metadata:

src/app/quest-summary.component.ts

// warning: few browsers support shadow DOM encapsulation at this time
encapsulation: ViewEncapsulation.Native

ShadowDom View 封装仅适用于原生支持影子 DOM 的浏览器(参见 Shadow DOM v1 网站上的 Can I use)。支持仍然有限,这就是为什么 Emulated View 封装是默认模式并在大多数情况下推荐

External and global style files

When building with the CLI, you must configure the angular.json to include all external assets, including external style files.

Register global style files in the styles section which, by default, is pre-configured with the global styles.css file.

See the CLI wiki to learn more.

关于css - Angular:组件样式不会级联到子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57761930/

相关文章:

html - 将容器的内容保持在一起

javascript - 悬停时滚动条跳跃

jquery - 使用 jquery 悬停更改显示属性

angular - 如何以 Angular 方式获取 Angular2 路由上的参数?

c# - asp.net C# 如何以编程方式更改 Page_Load 上的正文背景图像

angular - 在 Angular 7 项目中读取来自第三方服务器的 SAML 响应

html - 如何在 Angular 中不添加标签的情况下呈现一个innerHTML

html - 创建此 html block 的正确方法是什么

css - 如何从 Sass 中的 CSS 文件扩展类?

html - CSS z-index 在我的 Rails 5 应用程序中表现异常