How To Implement Angular Elements

Angular Elements are angular components that can be published as web components, making them easy to reuse on any hTML page. This article will show you how to implement angular elements in your web applications.

Angular Element is a new package in angular that helps us to publish angular components as custom elements. It does this by compiling the angular part into a web component. The Angular Elements functionality is available with the package @angular/elements.

Let’s get into implementation

1. Firstly, create a new project by hitting the command.

ng new angular-custom-elements-demo

2. Add elements package by hitting the command.

ng add @angular/elements

3. Then create a component.

ng g component button --inline-style --inline-template

4. After that, add properties to the component.

import { Component, OnInit ,EventEmitter, Input, OnChanges, Output, SimpleChanges, ViewEncapsulation} from '@angular/core';


@Component({

 selector: 'app-button',

 template: `

 <div>

 <h2 style="text-align:center">Mindbowser | Angular Elements</h2>

 <form style="margin-left: 410px;">

 <label>Name</label>

 <input type= "text" name = "Name"[(ngModel)] = "Name">

 <label>Email</label>

 <input type= "text" name= "Email"[(ngModel)] = "Email">

 <button (click)="handleClick($event)">{{ label }}</button>

 </form>

 </div>

`,

 styles: ['input[type=text], select {width: 50%;padding: 12px 20px;margin: 8px 0;display: flex;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box;}button {width: 50%;background-color: #24a0ed;color: white;padding: 14px 20px;margin: 8px 0;border: none;border-radius: 4px;cursor: pointer;}button:hover {background-color: #24a0ed;}div {border-radius: 5px;background-color: #f2f2f2;padding: 20px;}'],

 })

export class ButtonComponent implements OnChanges {

 @Input() label = '';

 @Output() action = new EventEmitter<String>();

 Name = '';

 Email = '';

  constructor() { }

 ngOnChanges(changes: SimpleChanges) {

     console.log(changes);

 }

 handleClick(event: any) {

     let details = `{Name: ${this.Name}, Email: ${this.Email}}`

     this.action.emit(details);

 }

}

5. Update NgModule.

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

import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { ButtonComponent } from './button/button.component';

import { createCustomElement } from '@angular/elements';

import { FormsModule } from '@angular/forms';

@NgModule({

 declarations: [

   AppComponent,

   ButtonComponent

 ],

 imports: [

   BrowserModule,

   AppRoutingModule,

   FormsModule

 ],

 entryComponents: [ButtonComponent],

 providers: []

})

export class AppModule {

 constructor(private injector: Injector) { }

 // to use this module for bootstrapping

 ngDoBootstrap() {

   // for converting an angular component together with its dependencies to a custom element

     const customElement = createCustomElement(ButtonComponent, {injector: this.injector});

     customElements.define('app-button', customElement);

 }

}

6. Here, we have removed the bootstrap array, which is set to AppComponent. Then, add the ButtonComponent as the entryComponent list. Then, we said ngDoBootstrap() to use this module for bootstrapping.

7. Angular provides createCustomElement() for converting an Angular component with its dependencies to a custom element. And it accepts two parameters.

👉 First, the angular component should be used to create the element.

👉 Second, a configuration object. This object needs to include the injector property set to the current Injector instance.

8. The next step is registering the newly created custom element in the browser.This is done by calling customElements.define().

9. customElements.define() needs two parameter.

👉 First parameter is of type string and contains the name of the element.

Passing the string ‘app-button’ means the custom element <app-button> will be registered and can be used in HTML code.

👉 The second parameter is the custom element which has been created before.

10. After that, we need to build our project. Also, we need to concatenate 4 files(runtime.js, scripts.js, polyfills.js and main.js). After doing the project, a static js file will be created. And this we need to include in <script> an HTML page to see if our custom element is working.

<!doctype html>

<html lang="en">

<head>

 <meta charset="utf-8">

 <title>AngularCustomElements</title>

 <script src="./custom-button-element.js"></script>

 <base href="/">

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

 <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

 <app-button label="Submit" ></app-button>

   <script>

     const button = document.querySelector('app-button');

     button.addEventListener('action', (event) => {

       console.log(`Action created: ${event.detail}`);

     });

   </script>

</body>

</html>

Hire AngularJS Developers

Importing Angular Element To Another Project

1. For this, we need to create a new Angular project by hitting the command.

ng new my-app

2. After that, we need to run the command.

npm install web-component-essentials

This command will install our Angular project’s web component and add an entry into the package JSON.

3. Once imported, add CUSTOM_ELEMENTS_SCHEMA from @angular/core to the application module.

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import 'web-component-essentials';

import '../assets/custom-button-element.js';

@NgModule({

 declarations: [

   AppComponent

 ],

 imports: [

   BrowserModule,

   AppRoutingModule

 ],

 providers: [],

 bootstrap: [AppComponent],

 schemas: [

   CUSTOM_ELEMENTS_SCHEMA // Tells Angular we will have custom tags in our templates

 ]

})

export class AppModule { }

4. Import the static js file that has been generated at our main project to the application module.

5. Then, copy the selector for a custom element from the index.js file of our main project, paste it and run our new project.

Here’s the Html File:

<h1 style="text-align: center;">Importing An Angular Element</h1>

<app-button #ButtonComponent label="Submit" formName="Form">

</app-button>

{{receivedData}}
import { Component, AfterViewInit, ElementRef} from '@angular/core';

@Component({

 selector: 'app-root',

 templateUrl: './app.component.html',

 styleUrls: ['./app.component.scss']

})

export class AppComponent {

 title = 'my-app';

 button: any;

 receivedData=''

constructor(private elementref: ElementRef){

}

ngAfterViewInit(){

 this.elementref.nativeElement.querySelector('app-button').addEventListener('action', (event: any) => {

   console.log(`Action created: ${event.detail}`);

   this.receivedData = event.detail

 });

}

}

This is the whole procedure, from creating an angular element to importing this into an entirely new project. Here’s the output.
Related Read : What Are Micro-Frontends And Steps To Implement Micro-Frontends In Angular

coma

Conclusion

We have seen how to implement Angular elements, and importing angular element to another project. Angular Elements are the future of Angular, and are part of the reason why Angular is so successful.

Keep Reading

Keep Reading

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?