我一直在使用 Angular Elements 并尝试尽可能实现最佳的浏览器兼容性。但是我似乎走到了死胡同,因为当我为 Shadow DOM 添加 IE polyfill 时,它会破坏 chrome 中的元素。
最初我遇到错误 'Failed to construct HTML element' ,所以我将 tsconfig.json 中的“目标”更改为 es2015/es6。
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}
组件
// @dynamic
@Component({
selector: 'flexybox-cardmanagement',
templateUrl: './card-management.component.html',
styleUrls: ['./card-management.component.scss'],
encapsulation: ViewEncapsulation.ShadowDom
})
更改目标碰巧破坏了 IE,因为不支持 es2015/es6+。所以我碰巧在@webcomponents 包中找到了custom-elements-es5-adapter,它包装了ES5,为需要它的浏览器提供必要的ES6 功能。然后我还必须添加对自定义元素的支持。
polyfills.ts
/*****************************************************************************************
* APPLICATION IMPORTS
*/
import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js';
import '@webcomponents/custom-elements/custom-elements.min';
此时它可以在 Chrome 中运行,但我在 IE 中收到以下错误
SCRIPT438: Object doesn't support property or method 'attachShadow'
所以我尝试通过在我的 polyfills.ts 中添加以下内容来为 Shadow DOM 添加 polyfill:
import '@webcomponents/shadydom';
这似乎解决了 IE 中的问题,但现在在 chrome 中给了我以下错误:
Uncaught TypeError: Cannot read property 'defineProperties' of undefined
最佳答案
让自定义元素在 IE11 中工作真的是一种折磨。我可能不会把你带到那里,但至少更进一步。
我认为您几乎做对了所有事情,我已经完成了相同的步骤,但是我使用了不同的 polyfill,所以也许您想尝试这些:
Angular .json
"scripts": [
// removed polyfill `document-register-element.js` that may be included with ng add @angular/elements
]
polyfills.ts
import '@webcomponents/shadydom/shadydom.min.js';
import '@webcomponents/custom-elements/src/native-shim';
import '@webcomponents/custom-elements/custom-elements.min';
要检查它是否可能是版本问题:
包.json (相关部分)
{
"dependencies": {
"@angular/**": "~7.2.1",
"@webcomponents/custom-elements": "^1.2.1",
"@webcomponents/shadydom": "^1.4.2",
"core-js": "^2.5.4",
}
}
信息:使用此配置,自定义元素适用于我的 Chrome、Firefox 和 IE11,但我无法在 IE11 中使用输出绑定(bind)。不知道为什么会这样,如果您对此感兴趣并找到解决方案,可以提供here .
IE11 的一般提示:
现在不是你的问题,但如果 IE11 抛出它的各种错误之一,它对我的使用有很大帮助
import 'core-js/shim'
在 polyfills.ts
.这会一次导入所有 shims 以检查 IE11 是否遗漏其中一个。如果是这样,你可以进一步解决它,如果不是,你知道你必须寻找其他地方。Angular Elements polyfill
如果你想继续使用 Angular 使用的 polyfill,你可以尝试使用版本
1.8.1
.我在某处(但不记得在哪里)读到更高版本目前导致 IE 出现问题。
关于angular - 同时在 chrome 和 IE11 中支持 Angular Element 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54764616/