1

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?

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 1
    That error you getting in stackblitz because you are not running in a native browser. I don't think you will get that error on a local dev environment. – Eldar Apr 10 '20 at 07:39

1 Answers1

2

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

Eldar
  • 9,781
  • 2
  • 10
  • 35
  • Very cool - Thank you! Is there any particular reason why customElements.define is called in the app.component instead of app.module? All the tutorial I have seen use ViewEncapsulation.Native? I noticed you are using either `Emulated` or none. Could you elaborate on why? – Ole Apr 10 '20 at 08:46
  • 1
    @Ole probably all the tutorials you seen so far were for local development environment. And nothing wrong with using `Native`. But in `Stackblitz` environment it wont work. And the `Emulated` value was for testing purposes to see if it is running. – Eldar Apr 10 '20 at 08:57