在angular项目中使用web-component ----How to use Web Components with Angular
原文: https://medium.com/@jorgecasar/how-to-use-web-components-with-angular-41412f0bced8
-------------------------------------------------------------
I already told you about Web Components and Frameworks and now we have to put it into practice so that you can see that it does not only work in theory. As you can see, according to Custom Elements Everywhere, Angular passes all the tests so it is a good candidate to implement the use of Web Components.
Everything developed during this article can be followed step by step in the jorgecasar/tutorial-webcomponents-angular repository.
We will start with a new application, for which you can use the comando ng new tutorial-webcomponents-angular
and open it in our favorite editor.
Adding Custom Elements Schema
First, we enable the Web Components in our project including CUSTOM_ELEMENTS_SCHEMA
in src/app/app.module.ts
:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import { AppComponent } from './app.component';@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
})export class AppModule { }
Adding polyfills
To ensure compatibility with older browsers it is necessary to include webcomponents polyfills.
First, install the dependency using NPM:
npm install --save @webcomponents/webcomponentsjs
Today we can not include it as a module in the polyfills.ts
so we have to do a more manual process. We must indicate to Angular that he must copy certain files as assets in the angular.json
file:
{
"glob": "{*loader.js,bundles/*.js}",
"input": "node_modules/@webcomponents/webcomponentsjs/",
"output": "node_modules/@webcomponents/webcomponentsjs"
}
The next thing is to add the script load in the index.html
.
<script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
And finally we must wait for the dependencies to load to start our app and thus make sure that the Web Components are ready to be used:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';import { AppModule } from './app/app.module';
import { environment } from './environments/environment';declare global {
interface Window {
WebComponents: {
ready: boolean;
};
}
}if (environment.production) {
enableProdMode();
}function bootstrapModule() {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
}if (window.WebComponents.ready) {
// Web Components are ready
bootstrapModule();
} else {
// Wait for polyfills to load
window.addEventListener('WebComponentsReady', bootstrapModule);
}
ES5 Support
ES5 Custom Elements classes will not work in browsers with native Custom Elements because ES5 classes can not extend ES6 classes correctly. So if you are going to serve your app using ES5 you will need to add this code snippet in the <head>
, just before the webcomponents script included before.
<!-- This div is needed when targeting ES5.
It will add the adapter to browsers that support customElements, which require ES6 classes --><div id="ce-es5-shim">
<script type="text/javascript">
if (!window.customElements) {
var ceShimContainer = document.querySelector('#ce-es5-shim');
ceShimContainer.parentElement.removeChild(ceShimContainer);
}
</script>
<script type="text/javascript" src="node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
</div>
With this we have our app ready to include Web Components, so let’s create one and check its compatibility.
Creating a Web Component
We are going to install lit-element
, an ultra-lightweight library for the creation of Web Components by Justin Fagnani.
npm i --save @polymer/lit-element
We created a simple component called wc-mood
:
class WebComponentsMood extends LitElement {
static get properties() {
return { mood: String }
}
_render({mood}) {
return html`
<style>
.mood { color: #1976d2; }
</style><h1>Web Components are <span class="mood">${mood}</span>!</h1>`;
}
}customElements.define('wc-mood', WebComponentsMood);
And finally, we import it in the typescript file of our component, in this case app.component.ts
:
import './wc-mood/wc-mood';
And we use it in the html of our component:
<my-element mood=”awesome”></my-element>
Testing the interaction with the Web Component
Now that we have the Web Component working, let’s try the interaction with it.
Set properties from Angular
The first test is to verify that the component reacts when a property is established from Angular. To do this, we create the mood
property and a randomMood
method that changes that property:
export class AppComponent {
moods: Array<string> = ['awesome', 'formidable', 'great', 'terrifying', 'wonderful', 'astonishing', 'breathtaking'];
mood: string;constructor() {
this.randomMood();
}randomMood() {
const index = Math.floor(Math.random()*this.moods.length);
this.mood = this.moods[index];
}
}
And we make the corresponding change in the html to establish the property and we make that by clicking on the Angular logo we establish another value to the property:
<wc-mood [attr.mood]="mood"></wc-mood>
<img (click)="randomMood()"/>
Listen to events from Angular
To complete the interaction, we will launch an event from the component to listen to it from Angular.
In the Web Component we will notify the changes in the properties sending the event:
_didRender(_props, _changedProps, _prevProps) {
this._notifyPropsChanges(_props, _changedProps);
}_notifyPropsChanges(_props, _changedProps) {
for(let prop in _props) {
this.dispatchEvent(
new CustomEvent(prop + '-changed', {
detail: { value: _changedProps[prop] }
})
);
}
}
For simplicity, we will notify all changes in the properties. And to standardize we will send the event [prop]-changed
where [prop]
is the name of the property, in our case mood
. We do this because it is the most logical from my point of view and also both Angular and Polymer use this pattern, so we can begin to standardize it 😜
Once we have made this change we can already hear the event from Angular. To verify that angular receives the event we will animate the Angular logo for 1 second using the following method:
isChanged: boolean = false;moodChanged() {
this.isChanged = true;
setTimeout(() => this.isChanged = false, 1000);
}
And we add the link in the html, listen to the event and assign the animated
class to the image:
<wc-mood [mood]="mood" (mood-changed)="moodChanged()"></wc-mood>
<img (click)="randomMood()" [class.animated]="isChanged" />
Two-way data binding
To crown things off and simplify the way to establish and listen to the event we can use the double data binding:
<wc-mood [(mood)]="mood"></wc-mood>
Angular, in this case, will hear the mood-changed
event and assign the value to the property. In this way we can call the moodChanged
method when the value changes:
private _mood: string;public get mood():string {
return this._mood;
}public set mood(value:string) {
if(this._mood !== value) {
this._mood = value;
this.moodChanged();
}
}
Demo
For you to see the operation here I leave the demo:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2018-10-17 M.2接口NVMe协议的固态硬盘读写速度是SATA接口的两倍
2018-10-17 linux shell的执行方式
2018-10-17 linux查看当前shell的方法
2018-10-17 linux 的空命令:(冒号)
2018-10-17 linux 基本命令学习
2018-10-17 linux 的命令 -exec 的使用
2016-10-17 html 自定义标签的作用