Create A Web Component in Angular 15
This is a very brief post to cover how to quickly go from 0 to 1 with native HTML web components using Angular 15.
Project Organization
There are many ways to do this and I am not a fan of calling any of them correct. However, for the purposes of this post, we will assume that we are working on a component that will be a part of a Micro Frontend and will be a stand-alone implementation.
So we’ll assume that the sole purpose of the angular project we’re working on here is purely for this one single element.
Project Config
1. You need an angular project open. So open one, or create one:
ng new name-of-your-project
2. Your project needs an npm package called ngx-build-plus. This is a neat tool I’ll cover more later.
ng add ngx-build-plus
3. This step isn’t required but I do it for ease of use. Add this next line to your package.json
"build-components:prod": "ng build --configuration=production --output-hashing=none --single-bundle=true"
Now you can type “npm run build-components:prod” into the terminal whenever you want to build your web components.
4. Update your app.module.ts to be setup for generating a web component.
5. update the index.html in the root of the project to look like this:
Completing step 5 will make it so that you can see in real-time when your updates are made to the component (in this example the component is called FoodFormComponent)
6. This is just an understanding step. When you run ‘npm run build-components:prod’ the compiler will update the directory dist. There will be a file called main.js. That is the file that contains the code for your web component. Wherever you choose to use your new web-component, you need to include that file in a script tag in the HTML if you are using it outside of an angular project. It may be possible to do this in other ways, this is how I’ve got it working so far.
Now you’re all set on the config. We’ve accomplished:
created or selected an angular project to work in and modify.
Added ngx-build-plus to the project, which is a part of how we get the bundle we are looking for (the output of the compilation/build process).
Created an npm script to trigger the build whenever we need it without typing a long command in.
updated the app.module.ts to function in a way where it outputs a web component.
update index.html so we can see changes to our web-component in real time as we update the code.
Learn how to access the code of the web-component after it’s built.
Conclusion
This post has covered how to set a project up to produce a web component and explained in step 6 how to access the compiled/built version of the component JS code so that it can be imported into other contexts and used as a native HTML Web Component.