Although there are a number of good web components compilers like Stencil and Polymer, this tutorial will mainly focus on using Angular Elements and how to use it to make a collapsible accordion web component.

Components previously make using Angular Elements could only be used with Angular but with the recent release, it can now be used as a true web component. By ‘true web component’, I mean the one which adheres to the specifications.

Web components are based on four main specifications:

Custom Elements: For designing and using new DOM elements. Shadow DOM: To Encapsulate styles and markup. i.e. Prevent conflict between the styles of the components and the other html elements. ES Modules: Specifies how to include and reuse JS files so that the project stays modular and performs well. HTML Template: Specifies how to declare fragments of markup that go unused at page load, but can be instantiated later on at runtime.

Steps to make a web component

I am using angular/cli version 7.1.4. To check your version use ng -v or ng version command in your terminal.

I tried to use the shiny new Ivy compiler, but it has some bugs and for some reason, the package size was larger than the one that the current angular compiler builds. In future releases of Angular, Ivy should be the default and hence I hope that the following steps won’t change.

Step 1: Setup a new angular project using the angular cli.

ng new accordion --prefix custom --routing=false

Open the project in your preferred editor or file manager and delete all the files in app folder except the app.module file.

Delete the selected files.

ng g component accordion --inline-template -v ShadowDom

The above command will generate a new component with ViewEncapsulation as ShadowDom. This allows creating separate DOM trees which are isolated from the main DOM tree and it also supports ‘slots’.

CSS and markup will stay confined to your component and won’t leak or conflict with the other components of the website. Add the angular/elements package. On the other hand, it becomes difficult to change the styles of the component.

Next, we will add the angular elements package to our project.

ng add @angular/elements

Step 2: Configure app.module.ts and prepare for elements.

In the @NgModule decorator, remove the bootstrap property and add the entryComponents array with your custom components.

@NgModule({

declarations: [

AccordionComponent

], imports: [

BrowserModule

],

providers: [],

entryComponents: [AccordionComponent] })

Below that we will have to define some configs related to our components and register each component that the final package will include.

export class AppModule {

constructor(injector: Injector) {

const acc = createCustomElement(AccordionComponent, { injector });

customElements.define('custom-accordion',acc);

} ngDoBootStrap() {} }

In tsconfig.json find the “target” property and change ‘es5’ to ‘es2015’.

{

...

“target”: “es2015”,

...

}

Step3: Add the HTML markup.

We are using an inline template since it is a small template.

@Component({

...

template: `

<button #el class="accordion" (click)="toggleHelper()">

<slot name="header">Default header</slot>

</button>

<div class="panel">

<slot name="details">Default details</slot>

</div>`,

...

})

A side note on slots

Slots can be used when you want content to be placed in specific locations in your template. There are two types of slots, default and named. We are using the named slot here.

Default Slot can be use if the user of the component will have only one place to put his markup.

<!--Component HTML -->

<img src=”…”>

<slot></slot>

Now HTML can be included inside the component and will be rendered below the image.

<!--Usage -->

<my-component>

<h1>Image Caption</h1>

</my-component>

Named Slots allow you to give reference names to different slots and hence more than one slot can be used. In your component, you need to add the name attribute as shown.

<!-- Component HTML -->

<h1><slot name=”header”>Default Header</slot></h1>

<p><slot name=”caption”>Default Caption</slot></p>

Now the end user of the web component can just pass a span that references the slot name and it will be rendered in the matching location.

<! — Usage →

<my-element>

<span slot=”caption”>Some cool caption</span>

<span slot=”header”>My Custom Header</span>

</my-element>

Step 4: Add the styles

This is just personal preferences and your CSS skills.

Step 5: Add the toggle logic in the typescript file

On the 2nd line we have an @Input() icon property which is not required for this example but if you want to add more features this is an important concept to know. This icon property will be available as an attribute for your web component. You can use it as

<custom-accordion icon='plus'></custom-accordion>

// accordion.component.ts export class AccordionComponent {

@Input() icon = 'arrow'; //this is not required.

@ViewChild("el", {read: ElementRef}) el: ElementRef; toggleHelper() {

this.el.nativeElement.classList.toggle("active");

var panel = this.el.nativeElement.nextElementSibling;

if (panel.style.maxHeight) {

panel.style.maxHeight = null;

} else {

panel.style.maxHeight = panel.scrollHeight + "px";

}

}

Step 6: Build and make a single package

ng build --prod --output-hashing=none

This will generate your web component in the dist/ folder. We will combine 4 files in one JavaScript package using the following command. Alternatively, you can add these scripts to the package.json build scripts.

cat dist/accordion/{runtime,polyfills,scripts,main}.js > elements.js

Step 7: Using your web component

The elements.js file that we generated in the previous step can be dropped in any framework or vanilla JS. We will make an index.html file to use it.

// index.html <!DOCTYPE html>

<html>

<head>

<title>My WebPage</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<script src="elements.js"></script>

</head> <body>

<custom-accordion icon="plus">

<span slot="header">A serious header</span>

<span slot="details">With some crucial details</span>

</custom-accordion>

<custom-accordion icon="plus">

<span slot="header">One more header</span>

<span slot="details">I ❤️ web</span>

</custom-accordion> </body>

</html>

Open the index.html file in chrome and admire your newly made web component. If you don’t see it, check the console and verify that the path to elements.js file is correct in the src attribute of the script tag.

Code to the final project is here.

Conclusion

You should now be able to make new components and convert existing angular components into reusable web components.

If you are going to make a very complex component, angular elements might be a good choice. For simple components, you can use a component compiler like Stencil, Polymer, etc. or just plain JS to make your web component.

If you think something could have been done in a better way, leave a comment and I hope you like the post. Thanks for reading! 👍