At Xello our host application is written in AngularJs. We have many different teams shipping code to our host application of varying sizes. Today we want to be shipping Angular, not AngularJs, and the following is what has worked best for us when integrating Angular with an AngularJs host. Keep in mind that we could also ship our app to any web page or framework like this.
My local environment node -v = v11.6.0 npm -v = 6.9.0
tldr: Here is the final project on github. git clone git@github.com:alexmgrant/ship-angular-app-as-web-component.git cd ship-angular-app-as-web-component npm i ng serve --open
Installation (from scratch) npm install -g @angular/cli ng new angular-elements cd angular-elements ng serve --open
Let’s set up our app to build as a native web component.
Add the @angular/elements package to your project. ng add @angular/elements
Next, we tell Angular which components we would like to build as custom elements (web components) using enteryComponents within app.module.ts.
Now we tell angular to create and define our custom element on boot within the constructor called with the ngDoBootstrap method. Your app.module.ts file should look like the following.
You should now see a blank screen on http://localhost:4200/. No worries, we need to replace <app-root></app-root> with our new web component within src/index.html.
We also need to add some polyfills to help browsers support web components. npm install @webcomponents/webcomponentsjs --save
No more blank screen and now we’re serving the app via a web component in our development environment 🥳
Now let’s take a look at routing because currently there are some issues/feature 🤷♀️ which stop the Angular router from working correctly within a web component.
Add a component and define a path, so it loads when we init our app.
ng g component home
You’ll notice the app does not load the new HomeComponent. We can fix that by explicitly passing the Angular router the current path. app.module.ts should look like the following.
Now our app inits with our homeComponent displaying. Let’s set up another route to test routing changes. We’ll make a lazy loaded module now so we can see everything works. ng g module lazy ng g component lazy
Now we can see everything works with the Angular router within a web component. 🎉
Next we optimize our build process for shipping our app.
First we change the build config within angular.json.
Next, we create a Node.js script to concat our build files into a single file so we can quickly ship our application. Create a file called build-angular-elements.js in the root of the project.
Install concat and fs-extra npm i concat fs-extra --save-dev
Create an npm script to build our angular app and run our concat script.
Now run our new build script. npm run build:angular-elements
Success, we now have our app built as a web component available in the root of our project under the angular-elements-build directory. Include these files into any website and enjoy!