gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:03:05 25 4
gpt4 key购买 nike

在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com