Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Create Your First Angular Element

DZone's Guide to

How to Create Your First Angular Element

Elements are a great way of creating reusable code/components, so you can develop faster. Read on for an intro to using elements in Angular.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Angular Elements allow us to create reusable Angular components, which can be used outside of the Angular application. You can use an Angular Element in any other application, built with HTML, React, etc. Essentially, Angular Elements are normal components, which are packaged as Custom Elements. You can learn more about Custom Elements here.

Angular Elements are reusable components, which can be used outside Angular. 

We will keep things simple in this post and, in a step-by-step manner, learn to create a basic Angular Element. So, let us get started.

Step 1: Installation

Create a new project using Angular CLI:

ng new demo1

Once the project is created, change the directory to demo1 and install Angular Elements. For that, run an npm command, as shown below:

npm install @angular/elements

To work with older browsers, we need a polyfill. So, let us install that also as shown below:

npm install @webcomponents/custom-elements

After installing the polyfill, open the polyfills.ts file and add these two entries:

import '@webcomponents/custom-elements/src/native-shim';
import '@webcomponents/custom-elements/custom-elements.min';

Step 2: Create the Component

In this step, we will create a reusable component, which would be used as an Angular Element.

  import {
       Component,
       Input
   } from '@angular/core';

   @Component({
       selector: 'app-message',
       template: `
 <h1 style='text-center'>{{title}}</h1>
  <h2>hey {{name}} loving Angular Elements {{answer}}</h2>
`,
       styles: ['h2 {color:red;}']
   })
   export class MessageComponent {
       title = 'Angular Elements';
       @Input() name: string;
       @Input() answer: string;
   }

MessageComponent is a very simple component with two properties decorated with the @Input() decorator.

Step 3: Register the Component

To register a component to be used as an Angular Element, we need to perform the following tasks:

  • Import the component.
  • Pass it in the declarations array.
  • Pass the component into the entryComponents array.
  • Do not pass any component into the bootstrap array.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MessageComponent } from './message.component';

 @NgModule({
     declarations: [
         MessageComponent
     ],
     imports: [
         BrowserModule
     ],
     providers: [],
     bootstrap: [],
     entryComponents: [MessageComponent]
 })
 export class AppModule {

 }

We do not need to bootstrap custom elements. They will be created automatically when added to the DOM and destroyed when removed from the DOM, however, they have to created somehow hence we are adding them into the entryComponents array. You must be knowing this property from dynamic component.

Step 4: Create Element From the Component

We need to invoke the  createCustomElement to create a custom element from an Angular Component. To do that, first import the following items in angular.module.ts:

import { NgModule, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';

After importing the required modules in the AppModule, we need to create custom element as shown in the listing below. Also, we are manually calling ngDoBootstrap.

export class AppModule {

      constructor(private injector: Injector) {
          const customElement = createCustomElement(MessageComponent, { injector });
          customElements.define('app-message', customElement);
      }

      ngDoBootstrap() {

      }
  }

Step 5: Use a Custom Element

Ideally, we would use a custom element in any external HTML file. In a future article, we will cover that. To use a custom element in the index.html file of the same Angular application, just place it in body, as shown below:

<body>
        <!-- <app-root></app-root> -->
        <app-message name="dj" answer="yes"></app-message>
</body>

Now run the application using the command ng serve and you should have a custom element rendered, as shown in below image:

Therefore, we can conclude that to work with Angular Custom Elements, we need to perform the following steps:

  1. Install @angular/elements. 
  2. Create a component.
  3. Register the component in entryComponent.
  4. Invoke createElement to create a custom element.
  5. Use it in your HTML.

I hope you found this post useful. Thanks for reading. If you like this post, please share it. Also, if you have not checked out Infragistics Ignite UI for Angular Components, be sure to do so! They have 30+ material based Angular components to help you code web apps faster.

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:
shadow dom ,angular ,angular elements ,web dev ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}