[Angular] Angular Elements Intro

Make sure install the latest Angular v6 with Angular CLI. Checkout ght Github for the code.

 

1. Create a new application:

of the 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:

of gc 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>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325325888&siteId=291194637