我最近一直在探索Angular组件的css和dom封装.
我使用ng-cli搭建了一个快速项目并加载了一个组件.假设组件选择器是“app-component”.这封装了与该组件本身相关的所有dom和css.到目前为止都很好.
我从之前的读物中学到的是,组件既不允许外部CSS流血,也不允许内部CSS流失(这更适用于Web组件)
现在,在index.html文件中我添加了一个bootstrap css文件,只是为了观察bootstrap css中的样式是否会渗透到组件中,令我惊讶的是它确实如此.我可以使用我的组件中提供的bootstrap css的所有类.
为什么会这样?基本上外部的css正在流入组件.我理解Angular中的视图封装概念,但这不适合.
听起来有点天真,但可能是我在这里错过了一点!
编辑
基本上我指的是这个:
https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom
这说:
Scoped CSS:在shadow DOM中定义的CSS是作用域的.样式规则不会泄漏,页面样式也不会流失.
解决方法:
Angular中默认不使用Shadow DOM.默认情况下,它根据ViewEncapsulation documentation通过“代理ID”进行模拟.
Emulated
Emulate
Native
scoping of styles by adding an attribute
containing surrogate id to the Host Element and pre-processing the
style rules provided via ViewMetadata or ViewMetadata, and adding the
new Host Element attribute to all selectors.This is the default option.
要在支持的浏览器上启用Shadow DOM,您必须使用ViewEncapsulation.Native
Native
Use the native encapsulation mechanism of the renderer.
For the DOM this means using Shadow DOM and creating a ShadowRoot for
Component’s Host Element.
例如:
import { ..., ViewEncapsulation } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss'],
encapsulation: ViewEncapsulation.Native
})
export class AppComponent ...
在这个Working Plunker #1中,你会注意到虽然已经在index.html(embedded)和style.css中实现了全局样式,并且在父代中实现了一种重写样式(具有更高的特异性),但这些样式并没有渗透到启用ViewEncapsulation.Native时的子项.
注意:我假设你没有使用ViewEncapsulation.Native,因为在原始问题中没有提到它.
特定选择器(类或id)不会被执行(如预期的那样),尽管更多“通用”样式.例如,应用于身体的字体系列会流入孩子(如果孩子不会覆盖它),因为我现在明白torazaburo在他的answer中提到了.
原文地址:https://codeday.me/bug/20190622/1265583.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。