How to transform an angular component to ‘custom elements’ , build it in single bundle , and call the script generated in other project

Anas Zeouinene
2 min readJun 20, 2022

--

As a developer, i don’t like wasting a lot of time on reading a very long documentation, specially when, i want just to fix a bug or implement a new feature… therefore, in this article, i’ll do my best to be as clear as possible, and presents the majors parts to acheive the goal, which is packaging angular components as custom elements (Web Component).

Creating a Custom Element

on Project A, we define a simple component (HeaderElementComponent in example bellow) that will be encapsulated in a custom element.

(don’t forget to add @angular/elements : ‘yarn add @angular/elements’)

HeaderElementComponent .ts:

HeaderElementComponent.html

app.module.ts

The function “createCustomElement ” will create a custom element class based on the component ‘HeaderElementComponent’ and the configuration’s injector ,which is used by default for each created instance.

After, creating the custom element, we must define it on the ‘CustomElementRegistry’, and mapping the given name (‘custom-element-header’ in our example) to the given constuctor (element).

Generate a single bundle

For that, we must install the library : ngx-build-plus

yarn add ngx-build-plus

and specify it as builder of the project on angular.json(Project A in our example)

“builder”: “ngx-build-plus:browser”,

you can also define your outputPath, example :

“outputPath”: “target/dist/header-elements”,

one all these elements are configured, you can execute build the project with single bundle option:
ng build <Project A> --single-bundle

a js file (main.js) will be generate in the outputPath , containing the project A.

Using the custom element :

To use my custom element, i will create a new Project B, which will call the script generated, and use my custom element.

on angular.json, add the script on the build options of Project B :

“scripts”: [“target/dist/header-elements/main.js”]

and call your element component by the name you define it :

<custom-element-header [text]=”’Yes it works!’”></custom-element-header>

To allow make our element allowed in NgModule, we must add CUSTOM_ELEMENTS_SCHEMA schema in the module which use our element

schemas: [CUSTOM_ELEMENTS_SCHEMA]

Well, that’s all… i whish i was clear , you just have to build and enjoy the power of Angular :)

You can also check the implementation of previous points in :
gitHub : https://github.com/azeouinene/angular-element-single-bundle

or
stackblitz : https://stackblitz.com/edit/angular-elements-single-bundle?file=src%2Fapp%2Fapp.component.ts

Thanks for reading
Anas ZEOUINENE

--

--