[Angular] Angular Elements Intro

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

 

1. Create a new application:git

ng new elementApp

 

2. Install @angular/elements package:github

ng add @angular/elements --project-name=<your_project_name>

 

3. Generate a component:web

ng g c course-title

 

4. Conver the element to angular elements: First we need to add our component to 'entryComponents'npm

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:app

// course title

constructor(
   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':ide

@NgModule({ imports: [ CommonModule ], ... schemas: [CUSTOM_ELEMENTS_SCHEMA] })

 

7. If you want to dynamic insert Angular Element into Angular application, such as:this

export class AppComponent { addEl() { const container = document.getElementById('container'); container.innerHTML = '<course-title></course-title>'; } }

You need to add polyfill in order to make it work:es5

npm i --save-dev @webcomponents/webcomponentsjs

Then add into polyfills.js:spa

.. * APPLICATION IMPORTS */ import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js';
相關文章
相關標籤/搜索