原文: 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 { }
chore(app): add custom elements schema · jorgecasar/tutorial-webcomponents-angular@8c60bf2
How to use Web Components with Angular
github.com

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);
}
chore(app): load polyfills · jorgecasar/tutorial-webcomponents-angular@6bc76a1
How to use Web Components with Angular
github.com

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>
feat(wc-mood): create web component · jorgecasar/tutorial-webcomponents-angular@bfd3b51
How to use Web Components with Angular
github.com

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()"/>
feat(wc-mood): set property to Web Component · jorgecasar/tutorial-webcomponents-angular@ff75f50
How to use Web Components with Angular
github.com

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

在angular项目中使用web-component ----How to use Web Components with Angular的更多相关文章

  1. angular项目中各个文件的作用

    原文地址 https://www.jianshu.com/p/176ea79a7101 大纲 1.对angular项目中的一些文件的概述 2.对其中一些文件的详细描述 2.1.package.json ...

  2. gulp 在 angular 项目中的使用

    gulp 在 angular 项目中的使用 keyword:gulp,angularjs,ng,ngAnnotate,jshint,gulpfile 最后附完整简洁的ng项目gulpfile.js 准 ...

  3. Angular 项目中如何使用 ECharts

    在有些使用 ECharts 库的 Angular 项目中,通常除了安装 npm 包之外,还会在 angular.json 中配置 “build.options.scripts”,将 “node_mod ...

  4. angular项目中遇到的问题

    一.angular项目中如何实现路由缓存 需要实现的效果,对请求的数据进行缓存,比如进入文章详情页之后点击返回,不会再调用后台数据接口:而是加载缓存中的数据,如何数据变动的情况下,可使用下拉刷新刷新页 ...

  5. angular项目中使用Primeng

    1.第一步把依赖添加到项目中 npm install primeng --save npm install @angular/animations --save npm install font-aw ...

  6. Angular项目中共享模块的实现

    创建share Modele:ng g m share import进来所有需要共享的模块都export出去, 一.共享CommonModule 暂时只有CommonModule,以后会有一些需要共享 ...

  7. Angular项目中引入jQuery

    npm install --save jquery npm install @types/jquery --save 在对应的组件中引入 import * as $ from "jquery ...

  8. 在angular项目中使用bootstrap的tooltip插件时,报错Property 'tooltip' does no t exist on type 'JQuery<HTMLElement>的解决方法和过程

    在angular4的项目中需要使用bootstrap的tooltip插件. 1. 使用命令安装jQuery和bootstrap npm install bootstrap jquery --save ...

  9. angular项目中使用jquery的问题

    1.使用npm命令往项目中添加jQuery. npm install jquery --save 2.在你想要用jQuery的组件中添加. import * as $ from "jquer ...

随机推荐

  1. 常见问题:MySQL/排序

    MySQL的排序分为两种,通过排序操作和按索引扫描排序. 按索引顺序扫描是一种很高效的方式,但使用的条件较为严格,只有orderby语句使用索引最左前列,或where语句与orderby语句条件列组合 ...

  2. php有关类和对象的相关知识2

    与类有关的魔术常量: __CLASS__,:获取其所在的类的类名. __METHOD__:获取其所在的方法的方法名. class A{ function f1(){ echo __CLASS__: / ...

  3. P1993 小K的农场(差分约束)

    小K的农场 题目描述 小K在MC里面建立很多很多的农场,总共n个,以至于他自己都忘记了每个农场中种植作物的具体数量了,他只记得一些含糊的信息(共m个),以下列三种形式描述: 农场a比农场b至少多种植了 ...

  4. 基因id转换

    DAVID网站提供了id转换的功能 1 选择上传gene list文件 2 选择上传ID的类型,我们ID-list.txt中的是Ensembl Gene ID,所以这里选ENSEMBL_GENE_ID ...

  5. IdentityServer4 学习三

    ClientCredentials客户端类型实现 客户端应用向IdentityServer请求AccessToken,IdentityServer验证通过把AccessToken返回给客户端应用,客户 ...

  6. C之typedef应用

    1.0关于typedef关键字的基础: https://www.cnblogs.com/anSn/p/8783347.html 1.1 typedef 修饰“函数类型” 的调用方法: 1)我们写一段普 ...

  7. 20191104-基于Python计数排序算法分析

    计数排序 计数排序算法没有用到元素间的比较,它利用元素的实际值来确定它们在输出数组中的位置,也就是说元素从未排序状态变为已排序状态的过程,是由额外空间的辅助和元素本身的值决定的,将每个元素出现的次数记 ...

  8. Dockerfile编写,以及设置一个自启动脚本

    FROM:指定基础镜像,必须为第一个命令 MAINTAINER: 维护者信息 RUN:构建镜像时执行的命令 ADD:将本地文件添加到容器中,tar类型文件会自动解压(网络压缩资源不会被解压),可以访问 ...

  9. 跟我一起学docker

    一.认识 1.什么是docker Docker 是一个开源项目,诞生于 2013 年初,最初是 dotCloud 公司内部的一个业余项目.它基于 Google 公司推出的 Go 语言实现. 项目后来加 ...

  10. Spring Cloud Alibaba学习笔记(1) - 整合Spring Cloud Alibaba

    Spring Cloud Alibaba从孵化器版本毕业:https://github.com/alibaba/spring-cloud-alibaba,记录一下自己学习Spring Cloud Al ...