Hello Angular 6 Elements

Yet another blog post on Angular 6 elements.

Quick Start

A starter “hello world” project can be found in GitHub. To build the element, checkout the project and run the following command:

>npm run build:elements

This should generate the file hello-world.js in the elements folder. To use the newly created Angular element, embed the javascript file in a html file:

<!DOCTYPE html>
<body>
 <hello-world></hello-world>
 <scr\ipt type="text/javascript" src="hello-world.js"></script>
</body>
</html>

NgModule

The hello-world element is implemented as a Angular component the same way as in an Angular app. To use it as a custom element outside of Angular, it is bootstrapped a bit differently in the app module file (app.module.ts)

...
import { createCustomElement } from '@angular/elements';
import { HelloWorldComponent } from './hello-world/hello-world.component';
@NgModule({  
     declarations: [HelloWorldComponent],
     imports: [BrowserModule],
     entryComponents: [HelloWorldComponent],
     providers: []})
export class AppModule {
 constructor(private injector: Injector) {
 }
 ngDoBootstrap() { 
     const el = createCustomElement(HelloWorldComponent, {
          injector: this.injector }); 
     customElements.define('hello-world', el); 
 }
}

Note the missing bootstrap attribute in the @NgModule definition for an Angular app. Instead the component is registered with the browser as a custom element in the ngDoBootstrap() method using the createCustomElement() API exported by @angular/elements package.

The building and export of custom elements in Angular 6 is still a work in progress. A custom script and build task (build:elements) from this blog post is used here to concatenate the output javascript files into the single hello-world.js file.

Advertisements

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.