Building Custom Elements or Web Components with Angular.

For building an angular custom element , you have some basic idea about angular.

What is angular custom Elements?

Angular elements are Angular components packaged as custom elements (also called Web Components), a web standard for defining new HTML elements in a framework-agnostic way. A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code.

Lets start

Create an Anguar Application If not known click here

ng new CustomElement

After successfully creation of application please move to the project folder on cmd

cd  CustomElement

Install angular element :

npm install @angular/elements --save.

Comment the selector in app.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
 
@Component({
 // selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  }

Write the following inside the app.component.html

<p>Hello My name is : {{fullname}}</p>
<form [formGroup]="test">
    <input type="text" formControlName="name">
</form>
<button class="btn btn-success" (click)='getName()'>Hello</button>

Write the follwoing inside app.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
 
@Component({
 // selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @Input() fullname: string;
  test: FormGroup;
  constructor(private fb: FormBuilder) { }
 ngOnInit(): void {
    this.test = this.fb.group({
      name: ['']
    });
  }
  getName() {
    alert('Hii your name is' + this.test.value.name);
  }
}

Remove AppComponent from bootstrap array in app.module.ts.

Put the AppComponent inside  entryComponent Array in    app.module.ts.

Import injector from @angular/core.

Import createComponent from @angular/elements.

write the following in doDoBootstrap()

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    NgbModule
  ],
  providers: [],
  bootstrap: [],
  entryComponents: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {
  constructor(private injector: Injector) {
 
  }
  ngDoBootstrap() {
    const el = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('greet-comp', el);
   }
}

Remove all the file from index.html and put the selector tag in it

<greet-comp fullname="swarup"></greet-comp>

Now run command ng serve to compile and run the application and you will see the following

For outside use build a javascript file inside the root folder like buid-script.js

Put the following code inside the buid-script.js file

const fs = require('fs-extra');
const concat = require('concat');
 
(async function build() {
 
    const files = [
        './dist/CustomElement/runtime-es2015.e8a2810b3b08d6a1b6aa.js',
        './dist/CustomElement/polyfills-es5.a73341bf449abbba4001.js',
        './dist/CustomElement/main-es5.680c0b778c755dd5cad2.js'
    ]
    await fs.ensureDir('elements')
    await concat(files, 'elements/hello-app-element.js')
    console.info('Angular Elements created successfully!')
 
})()

Run the command  npm install fs-extra concat –save-dev

Inside package.json update the following .

  "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
       "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e",
        "build:elements": "node build-script.js"
    },

Run command ng build –prod

Inside dist folder, see there is a folder name as your project name , inside this folder there is several js file are generated .

From which you have to add the complete path inside the buidscript.js as shown in the picture.

const fs = require('fs-extra');
const concat = require('concat');
 
(async function build() {
 
    const files = [
        './dist/CustomElement/runtime-es2015.e8a2810b3b08d6a1b6aa.js',
        './dist/CustomElement/polyfills-es5.a73341bf449abbba4001.js',
        './dist/CustomElement/main-es5.680c0b778c755dd5cad2.js'
 ]
    await fs.ensureDir('elements')
    await concat(files, 'elements/hello-app-element.js')
    console.info('Angular Elements created successfully!')
 
})()

Then run command npm run build: elements. Now see the element folder generated inside which there is a js file .name hello-app-element.js

Use the js file and your tag any project or outside an HTML file and see the result. See bellow

Result in the web

Thanks.

Leave a Reply

Your email address will not be published.

Back To Top