Angular ViewEncapsulation.ShadowDOM 不隔离 css 样式

Angular ViewEncapsulation.ShadowDOM doesn't isolate css styles

我读到 ShadowDOM 将阴影 dom 树与外部 css 隔离开来,所以我尝试在 Angular 中使用 ViewEncapsulation.ShadowDom,但似乎全局 css 仍在泄漏到阴影 DOM。

请在此处查看代码: https://stackblitz.com/edit/shadow-dom-test?file=src/app/app.component.ts

import { Component, VERSION, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
}

之后,在style.css中设置任何css都会影响AppComponent下的元素,即使封装设置为ViewEncapsulation.ShadowDom并且该组件包含在ShadowDom下树.

见下图,Font-size被Shadow下的元素继承DOM

来自w3 spec

3.3.2 Inheritance

The top-level elements of a shadow tree inherit from their host element

这意味着可继承的样式,如颜色或字体大小等,继续在阴影中继承 DOM,将穿透阴影 DOM 并影响组件的样式。

您可以使用

强制它回到初始状态

app.component.ts

:host {
  all: initial;
}

它将阻止继承而不影响影子DOM中定义的其他CSS。

Forked Stackblitz

另请参阅: