Building MicrofrontEnd Apps Using Angular Elements.
We will first create an angular application called “greetings”. Inside the greetings application we will be create a component called “hello-world”.
This is how the component looks like:
We will add below packages to the application:
ng add ngx-build-plus
ng add @angular/elements
@angular/elements enables us to package components as custom elements and ngx-build-plus is a build tool for angular.
After creating the component and adding the above dependencies, we will define the component in src/app/app.module.ts. This is how it looks like:
We will also install http-server via npm which will enable us to host our application via http.
npm i -g http-server — save
Build the Application
ng build --prod --output-hashing none --single-bundle true
–output-hashing (none) will avoid hashing the file names.
–single-bundle (true) will bundle all the compiled files into a single JS file.
Start the Server
http-server ./dist/greetings -p 8080
Using the custom element
We will create a container application called “container”. Inside the src/index.html we will use the custom element “app-hello-world” that we created above.
Here, Angular requires zone.js and custom-elements-es5-adapter.js provides custom element support within the browser. We also included main.js from our custom element.
Run the application using :
ng serve
This is what the final application looks like:
The complete code to this project can be found here: https://github.com/AbhiAgarwal192/MicrofrontEnd/tree/master/Angular
Happy Coding!!