我正在尝试基于浏览器初始化一个带有或不带有Shadow DOM的组件(因为IE不支持Shadow DOM)。
我检查它是否为IE11,并将IE的封装设置为Emulated,其他浏览器的封装设置为ShadowDom。
const agent = window.navigator.userAgent;
const isIe11 = agent.indexOf('MSIE') === -1 && agent.indexOf('Trident') > 0;
@Component({
selector: 'my-web-component',
templateUrl: '...html',
styleUrls: ['...scss'],
encapsulation: isIe11 ? ViewEncapsulation.Emulated : ViewEncapsulation.ShadowDom
})
export class NavbarComponent implements OnInit { ... }根据浏览器检查的返回值,isIe11的值是正确的,但封装始终以ViewEncapsulation.Emulated结束。
我通过DOM检查器确认了这一点,因为我在DOM中看不到#shadow-root。相反,我看到的是_ngcontent-c0,它确认封装是模拟的。
发布于 2019-04-18 20:34:11
按照你预想的方式,这是不可能的,因为angular以AOT模式编译你的代码,并且在编译过程中浏览器显然是未知的。
我只能想到一种方法来实现这一点。您必须将同一应用程序编译两次。一次用于非ShadowDom兼容的浏览器,另一次是可以实现的。
然后,在您的服务器上,您可以根据请求的浏览器提供所需的任何服务。我想你也可以在index.html中找到一种很好的方法来做这件事,它会根据当前浏览器加载正确的角度库。这将需要一些后ng build脚本。
不过,您可以在环境文件中处理所需的封装,因此,如果您对兼容和非兼容浏览器有两个不同的环境,则可以在您的环境中添加一个属性:
// non shadow dom compatible env
export const environment = {
// ...
defaultEncapsulation: ViewEncapsulation.Emulated
}
// shadow dom compatible env
export const environment = {
// ...
defaultEncapsulation: ViewEncapsulation.ShadowDom
}如果您有这两个用于生产构建的环境文件,则可以编辑main.ts中的bootstrapModule方法以读取值:
platformBrowserDynamic().bootstrapModule(AppModule, {
defaultEncapsulation: environment.defaultEncapsulation
});https://stackoverflow.com/questions/55745979
复制相似问题