Transform an Angular Component into a native Custom Element

Share this video with your friends

Send Tweet

Dynamic components aren’t always that easy, especially if you’d like to retrieve and instantiate them as part of an HTML coming from the server API. In this lesson we’re going to transform an Angular component into an Angular Element and dynamically insert it into the HTML by using the innerHTML property of a DOM element.

Note, if you get an error "Failed to construct 'HTMLElement': Please use the 'new' operator..", make sure to install the @webcomponents/webcomponentsjs polyfill and add the following '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'; at the end of polyfills.ts. I discuss this as well in the lesson.

Also check out this GitHub issue for more infos.

Wilgert Velinga
Wilgert Velinga
~ a year ago

Should we really instantiate the el in the constructor? Or is it actually better to do that in a lifecycle hook like ngOnInit?

Juri Strumpflohner
Juri Strumpflohnerinstructor
~ a year ago

@Wilgert Usually that’s fine, yes. I often also use the ngDoBootstrap hook. Basically as in the example of the video, rather than placing the code in the constructor, create a method in the Module class body called ngDoBootstrap and move the logic there.

...
export class AppModule {
  constructor(private injector: Injector) {}

  ngDoBootstrap() {
    const ngElement = createCustomElement(GreeterComponent, {
      injector: this.injector
    });
    customElements.define('do-greet', ngElement);
  }
}
Allamo
Allamo
~ a year ago

I get an error on intellisense: "Argument of type 'ngElementConstructor<unknown> is not assignable to parameter of type 'CustomElementConstructor'. ts(2345)