Create custom element in angular 6

Reading Time: 2 minutes

Loading

1) Create Angular Project

ng new <project name> --prefix custom --style=scss --skip-tests

2) Use schematics to add angular element support

ng add @angular/elements

3) Use angular-cli to generate new component and specify encapsulation is ViewEncapsulation.Native

4) REmove the document-create-element polyfill from script array.

5) Install custom-lements polyfill, “@webcomponents/custom-elements”

yarn add @webcomponents/custom-elements

6) Update polyfills.ts to include native-shim polyfill

// Shim for Browsers supporting Custom Elements
// Needed b/c Custom Elements ist defined for ES6+
// while we are downleveling to ES5.
import "@webcomponents/custom-elements/src/native-shim.js";

7) Include custom elements in entryComponents array of module

@NgModule({
  imports: [CommonModule, HttpClientModule, FormsModule, NgbModule],
  declarations: [
    InputTimeFormComponent,
    InputThemeComponent,
    ...
  ],
  entryComponents: [InputTimeFormComponent, InputThemeComponent],
  exports: [InputTimeFormComponent, InputThemeComponent]
})
export class TimeZoneModule {}

8) Assume the custom element uses Bootstrap 4 for styling. Then, import Bootstrap Sass in scss file of the component.

$icon-font-path: "../../../../node_modules/bootstrap-sass/assets/fonts/bootstrap/";
@import "~bootstrap/scss/bootstrap";

6) AppModule does not bootstrap or declare AppComponent. It also defines ngDoBoostrap function to register custom elements in custom element registry. createCustomElement creates custom element class based on Angular Component and define function of customElements registers the new custom element class.

import { BrowserModule } from "@angular/platform-browser";
import { NgModule, Injector } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpClientModule } from "@angular/common/http";
import { createCustomElement } from "@angular/elements";

import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import {
  InputTimeFormComponent,
  TimeZoneModule,
  InputThemeComponent
} from "./time-zone/";

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    NgbModule.forRoot(),
    TimeZoneModule
  ]
})
export class AppModule {
  constructor(private injector: Injector) {}

  ngDoBootstrap() {
    console.log("AppModule ngDoBootstrap");
    const timeConverterElement = createCustomElement(InputTimeFormComponent, {
      injector: this.injector
    });
    const timeThemeElement = createCustomElement(InputThemeComponent, {
      injector: this.injector
    });
    customElements.define("time-converter", timeConverterElement);
    customElements.define("time-theme", timeThemeElement);
  }
}

9) After AppModule is bootstrapped in main.ts, optionally assigns value to attribute of custom element

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .then(() => {
    const color = 'goldenrod';
    const themeChooser = document.getElementsByTagName("time-theme")[0];
    themeChooser.setAttribute("theme", color);

    const converter = document.getElementsByTagName("time-converter")[0];
    converter.setAttribute("theme", color);
  })
  .catch(err => console.log(err));

8) Build a nodeJS script to concatenate runtime.js, polyfill.js, script.js, main.js into time-converter.js. The time-converter.js can be used in other JS Frameworks and static website.


const fs = require("fs-extra");
const concat = require("concat");
(async function build() {
  const files = [
    "./dist/ng-time-converter/runtime.js",
    "./dist/ng-time-converter/polyfills.js",
    "./dist/ng-time-converter/scripts.js",
    "./dist/ng-time-converter/main.js"
  ];
  await fs.ensureDir("elements");
  await fs.emptyDir("elements");
  await concat(files, "elements/time-converter.js");
  await fs.copyFile(
    "./dist/ng-time-converter/styles.css",
    "elements/styles.css"
  );
  await fs.copy("./dist/ng-time-converter/assets/", "elements/assets/");
  await fs.copyFile("./src/demo.html", "elements/index.html");
  await fs.copyFile("CNAME", "elements/CNAME");
})();