Search code examples
javascriptangulartypescriptweb-componentangular-elements

Turning the Stackblitz HelloComponent into a Web Component?


Trying to turn the HelloComponent that comes with the Stackblitz Angular default project into a Web Component that runs in the same project.

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

Within the AppModule I've registered it like this:

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

  ngDoBootStrap() {

  }
}

And when the app compiles it generates the following error:

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

Not sure why. Any ideas? Also is it possible to run a web component in an Angular Project or does it have to be compiled by itself and then imported?


Solution

  • Well you need a few changed in order to make it work in a Stackblitz environment.

    First you need this package :

    @webcomponents/webcomponentsjs

    Then you need to add it to polyfills.ts

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

    And also you should remove the

    encapsulation: ViewEncapsulation.Native
    

    Stackblitz