Exploring Angular Elements

Lars Christian Stokholm von Qualen

Working with Angular in a mutli-page application setting, can be quite challenging. In this case i will focus on Angular en the context of a CMS. It is not important which CMS, but for the curious people out there, we are currently working in the context of EPIServer with a major danish energy company.

The client have used Angular for interactive components on their public website. It could be a component for calculating savings if you choose the clients product. Because the client has a lot of different offers, they had created just shy of 100 Angular applications and they had also created a custom build process using Gulp. The custom build process had ballooned in time and took about 20-30 minutes when using ahead-of-time compilation.

When LVQ Consult started working with the client the primary objectives were:

  • Transition into using Angular CLI for building.
  • Avoid building 100 separate applications.
  • Make it possible to use Angular as Web Components by just adding the element to the DOM. This would make it possible to make components that the website editors could easily use, because it would just be another HTML tag.

Angular Elements to the rescue!

In this article we will focus on how we got Angular to work as web components.

So what is Angular Elements anyways? The documentation says:

Angular elements are Angular components packaged as custom elements, a web standard for defining new HTML elements in a framework-agnostic way.

So the idea is that you will  be able to use Angular components like this:

<my-greeter first-name="John" last-name="Doe"></my-greeter>

The cool thing about components wrapped as Web Components is that they still go through the normal lifecycle, but it works by using plain DOM manipulation.

Angular Elements 101

First of all make sure you have a standard Angular CLI up and running, then run:

 ng add @angular/elements --name=*your_project_name*

This should add the necessary packages to you project.

Then all you need to do in order to register an Angular component as a Web Component is to somewhere call the following. This could be in a root component or AppModule.

// Convert `MyGreeterComponent` to a custom element.
const MyGreeterElement = createCustomElement(MyGreeterComponent, {injector});
// Register the custom element with the browser.
customElements.define('my-greeter', MyGreeterElement);

Et voilà! Or is it! We have run in to some issues getting this to work cross browser, specifically Internet Explorer 11.

We will go more in depth in the next couple of articles.