DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Achieving Micro-frontend Architecture Using Angular Elements
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • Beyond Algorithms: The Human Element in AI-Driven Cybersecurity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users

Trending

  • Threat Modeling Context-Aware AI: A STRIDE Walkthrough
  • The Real Cost of Change in Software Development
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • Building Enterprise File-Heavy AI Workflows: From Secure Uploads to Governed Document Intelligence

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. How to Create Your First Angular Element

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.

By 
Dhananjay Kumar
·
Aug. 05, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
16.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Element AngularJS

Published at DZone with permission of Dhananjay Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Achieving Micro-frontend Architecture Using Angular Elements
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • Beyond Algorithms: The Human Element in AI-Driven Cybersecurity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook