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]
})
[Angular] Angular Elements Intro
原文:https://www.cnblogs.com/Answer1215/p/8992242.html