此错误通常是由于 Angular 应用程序中的 Shadow DOM 和 Safari 浏览器中不支持的 'adoptedStyleSheets' 属性相互作用造成的。
解决该问题的一种方法是使用 polyfill 将 'adoptedStyleSheets' 属性添加到 Shadow DOM 中。可以使用 Web Components 兼容性 polyfill,该 polyfill 提供了对 Shadow DOM 和 'adoptedStyleSheets' 属性的支持。
下面是一个代码示例,演示如何在 Angular 应用程序中使用 Web Components 兼容性 polyfill。
首先,在 Angular 应用程序的 polyfills.ts 文件中添加以下代码:
import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'; import '@webcomponents/webcomponentsjs/webcomponents-bundle.js';
然后,在使用 'adoptedStyleSheets' 属性的组件中引入以下依赖项:
import * as ShadyCSS from 'shady-css';
import '@webcomponents/shadycss/entrypoints/apply-shim.js'; import '@webcomponents/shadycss/entrypoints/custom-style-interface.js';
接下来,在组件的构造函数中初始化 ShadyCSS:
constructor(private elementRef: ElementRef) { ShadyCSS.prepareTemplate(this.template(), this.componentName); ShadyCSS.styleElement(this.elementRef.nativeElement, this.componentName); }
最后,在组件的样式中使用 'adoptedStyleSheets' 属性:
this.shadowRoot.adoptedStyleSheets = [new CSSStyleSheet()];