Make sure install the latest Angular v6 with Angular CLI. Checkout ght Github for the code.
1. Create a new application:
ng new elementApp
2. Install @angular/elements package:
npm i @angular/elements --save
npm i @webcomponents/custom-elements --save
3. Import polyfills in polyfills.ts:
/*************************************************************************************************** * APPLICATION IMPORTS */ import ‘@webcomponents/custom-elements/src/native-shim‘; import ‘@webcomponents/custom-elements/custom-elements.min‘;
4. Generate a component:
ng g c user-poll
5. Conver the element to angular elements:
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: [UserPollComponent],
imports: [BrowserModule]
})
export class AppModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(UserPollComponent, { injector: this.injector });
customElements.define(‘user-poll‘, el);
}
}
6. Build process:
Install:
npm install fs-extra concat --save-dev
//elementApp/build-script.js const fs = require(‘fs-extra‘); const concat = require(‘concat‘); (async function build() { const files =[ ‘./dist/elementApp/polyfills.js‘, ‘./dist/elementApp/runtime.js‘, ‘./dist/elementApp/styles.css‘, ‘./dist/elementApp/main.js‘ ] await fs.ensureDir(‘elements‘) await concat(files, ‘elements/user-poll.js‘) console.info(‘Elements created successfully!‘) })()
//package.json "build:elements": "ng build --prod --output-hashing none && node build-script.js"
Run:
npm run build:element

After concat all the files, we got:

Then we can use it in a test index.html:
<user-poll></user-poll> <script src="elements/user-poll.js"></script>

Step 6. Now there is a new library can help to simplfy the process. checkout ngx-build-plus
[Angular] Angular Elements Intro
原文:https://www.cnblogs.com/Answer1215/p/8992242.html