Angular Elements – part 3 how to turn an Angular Component into an Angular Element

Last time I showed you how to generate a new component and add Angular Elements to the project. Today I’ll show you how to turn an Angular component into an Element.

Getting Started

First, we need our component to do something. Here’s the code.

I’ve added it to app.component.html like this.

Here’s the result you get by running ng serve.

Angular Element Magic

Now that we’ve created an Angular Component we can convert it to an Angular Element.

All the magic happens in the app.module.ts. Here’s what it looks like before.

Here’s what it looks like after it’s been converted to an Angular Element.

The changes are:

  • Line 2: The Injector has been imported
  • Line 4: createCustomElement has been imported
  • Line 13: has been replaced with entryComponents: [HelloWorldComponent]
  • Line 15 to Line 24: ngDoBootstrap has been overridden to call createCustomElement, passing in HelloWorldComponent.

Check everything is working by running a build: ng build –prod –output-hashing=none.

note: –out-hashing=none will stop webpack from generating unique filenames. I’ll explain why this is important next time.

What just happened?

Normally, when an Angular app starts up we bootstrap the app immediately. You can see this on line 12 of the original app.module.ts. But we don’t want this to happen with a Custom Element because that’s not how they work.

Instead, we have overridden ngDoBoostrap and added our own code. The purpose of this code is to wrap the Angular Component in a Custom Element wrapper (lines 19, 20 and 21) and then register the result with the browser (line 22).

Once registered, the browser will know which class to call when it encounters our <hello-world> tag.

Summary

Today I’ve shown you how easy it is to turn any Angular Component into a Custom Element.

Next time I’ll show you how to add the Element to any web page.

 

<< Read part 2 Read part 4 >>

 

Upgrade to Angular is a daily bite-size newsletter containing Angular newsanalysis and advice by Darryl Brown.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.