zoukankan      html  css  js  c++  java
  • [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:

    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';
  • 相关阅读:
    Java8 新特性 (七)
    Java8 新特性 (六)Optional 类
    Java8 新特性 (四)方法引用与构造器引用
    使用Postman做接口测试(一)
    使用unittest方法写登录接口,调用cookie
    python的简单实用二(封装/继承/多态)
    学习进度条46
    学习进度条104
    学习进度条103
    学习进度条102
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8992242.html
Copyright © 2011-2022 走看看