Unleashing the Power of Angular Web Components

Clearwater Analytics Engineering
cwan-engineering
Published in
6 min readJan 19, 2024

Angular is one of the well-known platforms for building web applications due to its key strengths, including robustness, maintainability, and power. One of these is the concept of Angular Web Components which are built on top of a set of technologies introduced by the web components specifications.

In this blog, we will dig deeper into Angular Web Components, why they matter, and how to utilize them to simplify your application development process.

What are Angular Web Components?

Web components are an extension of the HTML and DOM specification. They are inherently encapsulated into reusable components that can be incorporated into web pages and web applications. The design of web components can be overridden by the web page.

One of their strong points is that they are framework-agnostic, so they can be used in any JavaScript framework. This makes it possible to have a library of shared components while also having various platforms and technologies.

Web components are built on two major technologies:

1. Custom Elements

These are a fundamental part of web components and allow developers to define their own custom HTML elements. Once defined, custom elements behave just like built-in, native HTML elements.

2. Shadow DOM:

It allows encapsulation by hiding DOM behind a shadow root. This encapsulation isolates the component’s markup, style, and behavior, protecting it from outside influence and preventing it from impacting other parts of the web page. Each web component has its own isolated Shadow DOM tree, separate from the main document tree.

Why are they important?

Web components have become important because of their:

  • Reusability: Building a standard UI component that can be reused across multiple applications promotes efficiency and consistency.
  • Encapsulation: Custom elements keep the markup structure, style, and behavior hidden and separate from other code on the page so that various parts do not clash and the code can be kept clean and neat.
  • Interoperability: They work well with other technologies.

So, these points make it sensible to adopt web components rather than using the traditional iFrame.

But how are they different from iFrame?

Both web components and iFrames are technologies for encapsulating code, but they work in quite different ways:

  • Isolation: An iFrame supplies a high level of isolation, mainly embedding another webpage within your current page. Everything within an iFrame (HTML, CSS, JavaScript) operates in a separate context from the parent page. This is not the case with web components. Web Components reside in the same context as the rest of the page and have a direct relationship with the DOM.
  • Interaction: Because iFrames operate in a separate context, interactions between the parent page and the iFrame is a bit more complex. With web components, interactions with the rest of your application are more straightforward because web components communicate with the DOM directly, just like any other HTML element.
  • Size and Performance: iFrames carry overhead, as each iFrame embeds a full webpage, which can negatively affect performance. Web components are typically smaller and more lightweight, leading to better performance.
  • Styling: iFrames can be difficult to style and make responsive, as they don’t necessarily inherit styles from the parent page. On the other hand, web components can be styled just like any HTML element and can accept external styles, making them easier to integrate into the design of your site.

In general, Clearwater adopted web components as we wanted a reusable UI element that could interact seamlessly with our applications.

What triggered us to adopt Web Components in the Clearwater platform?

At Clearwater, we wanted to share similar user experiences for the same set of functionalities within various products because embedding a webpage within a product produces a great user experience rather than creating a new application. This retains user engagement by staying on the same URL with the same look and feel.

Creating Angular Web Components

Here’s a step-by-step guide to creating Angular Web Components:

1. Set up your Project: Start by creating a new Angular project if you don’t already have one set up. You can do this using the Angular CLI command:

ng new webcomponent-example

2. Create an Angular Component: Next, generate a new Angular component in your application.

ng generate component web

3. Register Component as a Custom Element: Once the component has been created, it can be registered as a Custom Element.

@NgModule({
declarations: [AppComponent, WebComponent],
})
export class AppModule implements DoBootstrap {
constructor(private readonly injector: Injector) {

//call the `createCustomElement()` method to transform the component to a custom element:
const webComponent = createCustomElement(WebComponent, { injector })
customElements.define('webcombonent-widget', webComponent)
}
ngDoBootstrap() {
//code for local development
}
}

4. Build and Package your component
After adding the code for converting our Angular component to a custom element, let’s now build the web component so we can use it in other projects without depending on Angular.

ng build — prod — output-hashing none

The — output-hashing none is to keep the file name consistent each time you make changes and build the project.

5. Concatenate the Output Files
After building, you’ll have a few output files. These need to be concatenated into one main file that can be easily imported into any application.

Inside the root of your project, create a build-component.js file and add the following code:

const fs = require('fs-extra')
const concat = require('concat')

build = async () => {
const files = ['./dist/runtime.js', './dist/polyfills.js', './dist/main.js']

await fs.ensureDir('dist')
await concat(files, 'dist/security-mapping-ui.js')
}
build()

Your Angular Web Component is now created and packaged into dist/webcomponent-widget.js.

We can host this bundled file on any server, making it convenient to be used by other applications. This file can be used as a script in any HTML file, and your component can be used by its custom element name in your main application.

Using our Web Component in other applications

To use your newly created and packaged web component in an Angular application, we import the hosted JavaScript files using a <script> tag, and we call the component using the <webcomponent-widget> tag (this is the name we specified for our custom element in the customElements.define() method inside the constructor of AppModule.

<webcomponent-widget> </webcomponent-widget>

Conclusion

Angular Web Components offer a powerful way to create reusable, testable, and encapsulated pieces of UI, providing a flexible way to build large-scale, maintainable applications. Though you’re packaging your components as web components, you’re not losing access to Angular’s features like dependency injection, data binding, and services.

About the Author

Snehil Sahu is a Senior Software development Engineer at Clearwater Analytics with over 10 years of experience in Software Engineering. He has experience in working on large scale distributed applications and comes from financial and e-commerce background.
In his free time he loves binge watching sitcoms and spending quality time with his family.

--

--