Angular 元素就是打包成自定义元素的 Angular 组件。所谓自定义元素就是一套与具体框架无关的用于定义新 HTML 元素的 Web 标准。
自定义元素这项特性目前受到了 Chrome、Edge(基于 Chromium 的版本)、Opera 和 Safari 的支持,在其它浏览器中也能通过腻子脚本加以支持。
自定义元素扩展了 HTML,它允许定义一个由 JavaScript 代码创建和控制的标签。 浏览器会维护一个自定义元素的注册表 CustomElementRegistry,它把一个可实例化的 JavaScript 类映射到 HTML 标签上。
创建angular工作空间
ng new workspace_name --create-application=false
安装Angular Elements
ng add @angular/elements --project=project_name
安装ngx-build-plus插件(目的将打包产生的runtime.js等多个js合并成一个js)
ng add ngx-build-plus --project=project_name
处理AppModule
@NgModule({declarations: [AppComponent],imports: [BrowserModule],providers: [],// bootstrap: [AppComponent]})export class AppModule {constructor(private injector: Injector){}ngDoBootstrap(){const customElement = createCustomElement(AppComponent,{injector: this.injector});customElements.define("my-element",customElement);}}
在package.json添加一条新的script
"script": {...,"build:my-custom-element": "ng build --prod --output-hashing=none --single-bundle"}

此时在dist文件中就会产生自定义HTML标签的main.js
支持Angular 中的@Input() @Output()装饰器
import { Component, EventEmitter, Input, NgZone, Output } from '@angular/core';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})export class AppComponent {title = 'test-custom-element';@Input() inputProperty;@Output() clickThing = new EventEmitter();constructor(private zone: NgZone){}clickMethod(){this.clickThing.emit("output测试中");this.zone.runOutsideAngular(() => {});}}
window.onload = () => {const element = document.getElementById("test");element.inputProperty = '44444444444';element.addEventListener('clickThing',(ev) => alert(ev.detail));}
在Angular项目中引入自定义元素
在angular项目添加@angular-extensions/elements
ng add @angular-extensions/elements
在AppModule中引入LazyElementsModule
import { LazyElementsModule } from '@angular-extensions/elements';import { CUSTOM_ELEMENTS_SCHEMA, Injector, NgModule } from '@angular/core';import { createCustomElement } from '@angular/elements';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component';@NgModule({declarations: [AppComponent,],imports: [BrowserModule,LazyElementsModule // 引入],schemas: [CUSTOM_ELEMENTS_SCHEMA], // 引入providers: [],bootstrap: [AppComponent]})export class AppModule {}
在component.html中添加指令即可
<my-element *axLazyElement="elementUrl"></my-element><!-- elementUrl指的是自定义元素的js地址 -->
在非Angular项目中引入自定义元素
在原生html,React,Vue项目中引入打包产生的js,还需要引入zone.min.js。
MDN链接🔗 : https://developer.mozilla.org/zh-CN/docs/Web/API/Window/customElements
