将 Stackblitz HelloComponent 变成 Web 组件?

Turning the Stackblitz HelloComponent into a Web Component?

正在尝试将 Stackblitz Angular 默认项目附带的 HelloComponent 转换为同一项目中 运行 的 Web 组件。

https://stackblitz.com/edit/angular-custom-elements-hello?file=src%2Fapp%2Fapp.module.ts

AppModule 中,我是这样注册的:

export class AppModule { 
  constructor(injector:Injector) {
    const hello = createCustomElement(HelloComponent, { injector }) 
    customElements.define('h-c', hello)
  }

  ngDoBootStrap() {

  }
}

当应用程序编译时会生成以下错误:

AppComponent.html:1 ERROR TypeError: hostEl.createShadowRoot is not a function

不知道为什么。有任何想法吗?也可以在Angular项目中运行一个web组件,还是必须自己编译然后导入?

好吧,您需要进行一些更改才能使其在 Stackblitz 环境中运行。

首先你需要这个包:

@webcomponents/webcomponentsjs

然后需要添加到polyfills.ts

import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'

而且你还应该删除

encapsulation: ViewEncapsulation.Native

Stackblitz