[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:
1 2 3 4 5 6 7 8 9 10 | // 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';
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-02-13 [Gatsby] Install Gatsby and Scaffold a Blog
2017-02-13 [Redux] Avoid action type naming conflicts
2017-02-13 [CSS] Get up and running with CSS Grid Layout
2017-02-13 [React] Render Basic SVG Components in React
2017-02-13 [NativeScript] Style NativeScript views using the default core theme