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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Achieving Micro-frontend Architecture Using Angular Elements
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • Playwright: Filter Visible Elements With locator.filter({ visible: true })
  • Rediscovering Angular: Modern Advantages and Technical Stack

Trending

  • AI’s Role in Everyday Development
  • Fixing Common Oracle Database Problems
  • Teradata Performance and Skew Prevention Tips
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  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 user avatar
Dhananjay Kumar
·
Aug. 05, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
16.4K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Achieving Micro-frontend Architecture Using Angular Elements
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • Playwright: Filter Visible Elements With locator.filter({ visible: true })
  • Rediscovering Angular: Modern Advantages and Technical Stack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!