Site icon TAAGUNG

Creating Web Components in Angular

Web Component in Angular

Web Component in Angular Introduction

What are Web Components?

According to the angular website – Angular elements are Angular components packaged as custom elements (also called Web Components), a web standard for defining new HTML elements in a framework-agnostic way.

What we are trying to do today?

We will create a main angular application and another application with a web component. We will then use this web component in our main angular application by just writing <webcomponent-widget></webcomponent-widget>.

Creating the main angular application.
ng new mainapplication
Creating the web component application
ng new webcomponent

We will change the app.component.html empty as below to avoid confusion later on-

We will need to add the below library for creating custom elements.

ng add @angular/elements --project webcomponent

We will create a new component in webcomponent.

We can now test if the demo component works by doing ng serve —

Transforming the component to a custom element-

Import injector and createCustomElement.

When you build an app, there are a couple of javascript files created. We will install the following package so that we can concatenate all the javascript files into one.

 npm install --save-dev concat fs-extra

Inside the root of your project, create a build-component.js file and add the following code:

const fs = require('fs-extra');
const concat = require('concat');

build = async () =>{
    const files = [
        './dist/webcomponent/main-es5.js',
        './dist/webcomponent/main-es2015.js',
        './dist/webcomponent/polyfills-es5.js',
        './dist/webcomponent/polyfills-es2015.js',
        './dist/webcomponent/runtime-es5.js',
        './dist/webcomponent/runtime-es2015.js',
      ];
    
      await fs.ensureDir('widget');
      await concat(files, 'widget/webcomponent-widget.js');
}
build();

If in your dist folder, after building the project, some other js files are created modify the above code accordingly.

Next, add a script to the package.json file of your Angular project as follows:

  "scripts": {
        "build:component": "ng build --prod --output-hashing none && node build-component.js",  
      },

Finally, you can run your script to build your project and concatenate the files into one JavaScript file that can be used wherever you want to use your web component to display news. Head back to your terminal and run the following command:

npm run build:component

You will find that in the widget folder there is a webcomponent-widget.js file created. Copy this file to the asset folder of the main application.

When you do ng serve for the main application, you can see that the main application is able to access the webcomponent

References-

Exit mobile version