Make sure install the latest Angular v6 with Angular CLI. Checkout ght for the code.
1. Create a new application:
ng new elementApp
2. Install @angular/elements package:
ng add @angular/elements --project-name=
3. Generate a component:
ng g c course-title
4. Conver the element to angular elements: First we need to add our component to 'entryComponents'
import { BrowserModule } from '@angular/platform-browser';import { NgModule, Injector } from '@angular/core';import { createCustomElement } from '@angular/elements';import { AppComponent } from './app.component';import { UserPollComponent } from './user-poll/user-poll.component';@NgModule({ declarations: [ UserPollComponent], entryComponents: [CourseTitleComponent], imports: [BrowserModule]})export class AppModule { constructor(private injector: Injector) {}}
5. Connect Custom Element Web API inside our component:
// course titleconstructor( private injector: Injector)} ngOnInit() { const htmlElement = createCustomElement(CourseTitleComponent, {injector: this.injector}); customElements.define('couse-title', htmlElement )}
6. Now the Angular Element should already work in the broswer. If we want to use Angular Element inside Angular Application, we should add 'schemas':
@NgModule({ imports: [ CommonModule ], ... schemas: [CUSTOM_ELEMENTS_SCHEMA]})
7. If you want to dynamic insert Angular Element into Angular application, such as:
export class AppComponent { addEl() { const container = document.getElementById('container'); container.innerHTML = ''; }}
You need to add polyfill in order to make it work:
npm i --save-dev @webcomponents/webcomponentsjs
Then add into polyfills.js:
.. * APPLICATION IMPORTS */import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js';