[Angular] Angular Elements Intro

早过忘川 提交于 2020-04-28 06:58:40

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:

ng add @angular/elements --project-name=<your_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 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':

@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 = '<course-title></course-title>';
  }
}

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';

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!