Angular Elements – part 4 how to add an Angular Element to any webpage, outside of an Angular project

Last time I showed you how to generate a custom element with Angular. This time I’ll show you how to embed an Angular Element in any webpage outside of an Angular project.

Getting Started

To build an Angular Element use the following command: ng build –prod –output-hashing=none

Once the build has finished the dist folder will look like this.

To deploy the web component, add the tag to the webpage: <hello-world name=”Angular Element”></hello-world>. Then include all the files from the dist folder:

If (like me) you aren’t impressed with the number of files you have to deploy, there is a simple solution. Just roll them into one file. A simple batch script will do:

copy ..\dist\hello-world\runtime.js + ..\dist\hello-world\polyfills.js +..\dist\hello-world\scripts.js + ..\dist\hello-world\main.js hello-world.js 

Sample Code

If you want to inspect the code, kick the tyres and build your own Angular Element you can download the source code from GitHub.

Summary

Angular Elements let you use any Angular Component, in any HTML page, outside of an Angular project. They currently suffer from package size and a lack of CLI support but the Angular team have promised Angular 7 will solve these issues. In the meantime get familiar with the concepts and use them in your Angular sites to improve code separation.

 

<< Read part 3 Read part 5 >>

 

Upgrade to Angular is a daily bite-size newsletter containing Angular newsanalysis and advice by Darryl Brown.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.